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

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →