Cube Summation


Problem Statement :


You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries.

UPDATE x y z W
updates the value of block (x,y,z) to W.

QUERY x1 y1 z1 x2 y2 z2
calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coordinate between y1 and y2 (inclusive) and z coordinate between z1 and z2 (inclusive).

Input Format
The first line contains an integer T, the number of test-cases. T testcases follow.
For each test case, the first line will contain two integers N and M separated by a single space.
N defines the N * N * N matrix.
M defines the number of operations.
The next M lines will contain either

 1. UPDATE x y z W
 2. QUERY  x1 y1 z1 x2 y2 z2 
Output Format
Print the result for each QUERY.

Constrains
1 <= T <= 50
1 <= N <= 100
1 <= M <= 1000
1 <= x1 <= x2 <= N
1 <= y1 <= y2 <= N
1 <= z1 <= z2 <= N
1 <= x,y,z <= N
-109 <= W <= 109

Sample Input

2
4 5
UPDATE 2 2 2 4
QUERY 1 1 1 3 3 3
UPDATE 1 1 1 23
QUERY 2 2 2 4 4 4
QUERY 1 1 1 3 3 3
2 4
UPDATE 2 2 2 1
QUERY 1 1 1 1 1 1
QUERY 1 1 1 2 2 2
QUERY 2 2 2 2 2 2
Sample Output

4
4
27
0
1
1



Solution :



title-img


                            Solution in C :

In C ++ :





#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<string>
#include<string.h>
#include<cstring>
#include<stack>
#include<queue>
#include<cassert>
#include<cmath>
using namespace std;

#define LL long long int
#define PII pair<int,int>
#define PB push_back
#define MP make_pair
#define INF 1000000000
#define debug(args...) do {cerr << #args << ": "; dbg,args; cerr << endl;} while(0)

LL BIT[110][110][110];
LL old[110][110][110];

void update(int x, int y,int z, LL w){ 
    int i,j,k;
    x += 5;
    y += 5;
    z += 5;
    for(i=x;i<110;i+=(i&-i)){
        for(j=y;j<110;j+=(j&-j)){
            for(k=z;k<110;k+=(k&-k))
                BIT[i][j][k] += w;
        }
    }
}

LL query(int x, int y, int z){
    int i,j,k;
    LL ret =0;
    x += 5;
    y += 5;
    z += 5;
    for(i=x;i>0;i-=(i&-i)){
        for(j=y;j>0;j-=(j&-j)){
            for(k=z;k>0;k-=(k&-k))
                ret += BIT[i][j][k];
        }
    }
    return ret;
   
}
int main(){
    int t,n,m,x,y,z,w;
    scanf("%d",&t);
    string type;
    while(t--){
        memset(BIT,0,sizeof(BIT));
        memset(old,0,sizeof(old));
        cin >> n >> m;
        while(m--){
            cin >> type;
            if(type == "UPDATE"){
                scanf("%d %d %d %d",&x,&y,&z,&w);
                update(x,y,z,w-old[x][y][z]);
                old[x][y][z] = w;
            }
            else{
                int x1,y1,z1,x2,y2,z2;
                scanf("%d %d %d %d %d %d",&x1,&y1,&z1,&x2,&y2,&z2);
                printf("%Ld\n",
                        query(x2,y2,z2) -
                        query(x2,y2,z1-1) - 
                        query(x2,y1-1, z2) - 
                        query(x1-1, y2, z2) + 
                        query(x1-1, y1-1, z2) + 
                        query(x1-1, y2, z1-1) + 
                        query(x2, y1-1, z1-1) -
                        query(x1-1,y1-1,z1-1)
                        );
            }
        }
    }
    
    return 0;
}







In Java  :





import java.util.Scanner;
public class Solution {
  Scanner sc = new Scanner(System.in);

  public static void main(String[] args) {
    new Solution().ss();
  }

  private void ss() {
    int nrt = sc.nextInt();
    for (int i = 0; i < nrt; i++) {
      solve();
    }
  }

  long mat[][][];
  int n;

  private void update(int x, int yy, int zz, long val) {
    while (x <= n) {
      int y = yy;
      while (y <= n) {
        int z = zz;
        while (z <= n) {
          mat[x][y][z] += val;
          z += (z & -z);
        }
        y += (y & -y);
      }
      x += (x & -x);
    }
  }

  private long sum(int x, int yy, int zz) {
    long rez = 0;
    while (x > 0) {
      int y = yy;
      while (y > 0) {
        int z = zz;
        while (z > 0) {
          rez += mat[x][y][z];
          z -= (z & -z);
        }
        y -= (y & -y);
      }
      x -= (x & -x);
    }
    return rez;
  }

  private void solve() {
    n = sc.nextInt();
    int m = sc.nextInt();
    mat = new long[101][101][101];
    long[][][] actual = new long[101][101][101];
    for (int i = 0; i < m; i++) {
      String op = sc.next();
      if (op.equals("UPDATE")) {
        int x = sc.nextInt(), y = sc.nextInt(), z = sc.nextInt();
        long w = sc.nextLong();
        //        x--; y--; z--;
        update(x, y, z, w - actual[x][y][z]);
        actual[x][y][z] = w;
      } else {
        int x1 = sc.nextInt(), y1 = sc.nextInt(), z1 = sc.nextInt();
        int x2 = sc.nextInt(), y2 = sc.nextInt(), z2 = sc.nextInt();
        //        x1--; y1--; z1--;
        //        x2--; y2--; z2--;
        long v1 = sum(x2,y2,z2)- sum(x1-1,y2,z2)  - sum(x2,y1-1,z2) + sum(x1-1,y1-1,z2);
        long v2 = sum(x2,y2,z1-1) - sum(x1-1,y2,z1-1) - sum(x2,y1-1,z1-1)  + sum(x1-1,y1-1,z1-1);
        System.out.println(v1 - v2);
      }
    }
  }
}









In  C :







#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define max 3001
#define max1 101
int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int t,n,m,x1,x2,y1,y2,z1,z2;
    int i,j,k,x[max],y[max],z[max];
    long W[max];
    char str[7];
    scanf("%d",&t);
    j=0;
    while(t--)
    {
        long mat[max1][max1][max1]={0};
        scanf("%d%d",&n,&m);
        for(i=0;i<m;i++)
        {
            scanf("%s",str);
            if(str[0]=='U')
            {
                scanf("%d%d%d%ld",&x[j],&y[j],&z[j],&W[j]);
                mat[x[j]][y[j]][z[j]]=W[j];
                j++;
            }
            else
            {
                scanf("%d%d%d%d%d%d",&x1,&y1,&z1,&x2,&y2,&z2);
                long sum=0;
                for(k=0;k<j;k++)
                {
                    if(x[k]>=x1 && x[k]<=x2)
                    {
                        if(y[k]>=y1 && y[k]<=y2)
                        {
                            if(z[k]>=z1 && z[k]<=z2)
                            {
                                if(W[k]==mat[x[k]][y[k]][z[k]])
                                    sum+=W[k];
                            }
                        }
                    }
                }
                printf("%ld\n",sum);
            }
        }
    }
    return 0;
}








In Python3 :





numTests = int(input())

#Making the data structure
cube = [];
for i in range(0, 100):
    cube.append([]);
    for j in range(0, 100):
        cube[i].append([])
        for k in range(0, 100):
            cube[i][j].append(0)
while numTests != 0:
    indexList = [[0,0,0,0]]
    line = input()
    tokens = line.split(' ')
    N = int(tokens[0])
    numOp = int(tokens[1])
                  
    #Updating the data structure according to the queries
    while numOp != 0:
        query = input()
        tokens = query.split(' ')
        if(tokens[0] == 'UPDATE'):
            x = int(tokens[1]) - 1
            y = int(tokens[2]) - 1
            z = int(tokens[3]) - 1
            w = int(tokens[4])
            cube[x][y][z] = w
            tempList = []
            tempList.append(x)
            tempList.append(y)
            tempList.append(z)
            tempList.append(w)
            flag = 0
            for index in indexList:
                if index[0] == x and index[1] == y and index[2] == z:
                    index[3] = w
                    flag = 1
            if flag == 0:
                indexList.append(tempList)
                            
        elif(tokens[0] == 'QUERY'):
            x1 = int(tokens[1]) - 1
            y1 = int(tokens[2]) - 1
            z1 = int(tokens[3]) - 1
            x2 = int(tokens[4]) - 1
            y2 = int(tokens[5]) - 1
            z2 = int(tokens[6]) - 1
            sum = 0
            for index in indexList:
                if index[0] >= x1 and index[0] <= x2:
                    if index[1] >= y1 and index[1] <= y2:
                        if index[2] >= z1 and index[2] <= z2:
                            sum += index[3]
            print(sum)
        numOp -= 1
    
    numTests -= 1
                        








View More Similar Problems

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →