三维树状数组(区间更新,单点查询)POJ

来源:互联网 发布:知乎消失的夫妻原文 编辑:程序博客网 时间:2024/05/29 15:54

Problem Description
Given an N*N*N cube A, whose elements are either 0 or 1. A[i, j, k] means the number in the i-th row , j-th column and k-th layer. Initially we have A[i, j, k] = 0 (1 <= i, j, k <= N). 
We define two operations, 1: “Not” operation that we change the A[i, j, k]=!A[i, j, k]. that means we change A[i, j, k] from 0->1,or 1->0. (x1<=i<=x2,y1<=j<=y2,z1<=k<=z2).
0: “Query” operation we want to get the value of A[i, j, k].
 

Input
Multi-cases. First line contains N and M, M lines follow indicating the operation below. Each operation contains an X, the type of operation. 1: “Not” operation and 0: “Query” operation. If X is 1, following x1, y1, z1, x2, y2, z2. If X is 0, following x, y, z.
 

Output
For each query output A[x, y, z] in one line. (1<=n<=100 sum of m <=10000)
 

Sample Input
2 51 1 1 1 1 1 10 1 1 11 1 1 1 2 2 20 1 1 10 2 2 2
 

Sample Output
101

      树状数组学了好久了,也做了好几个题,今天想起来写博客才发现是第一个,看来之前是疏乎了。

      这是一道三维的树状数组,刚看起来很难的,不过说起来几维都是一样的,不过是个循环多少层的问题罢了。在区间更新的时候,要注意的是一维是直接减;二维是减两部分再加上那部分重复减掉的,画一个图,小学生就可以理解的道理;三维自然也是要减完再加上重复减掉的地方的,但是这里就抽象了很多,我找到这个关键,是画了三遍正方体后才成功的,不过画的难看,也不会贴图,所以就不上图了。至于这个规律在代码里体现出来,其实看一看大概就能明白的。

代码如下:

#include<cstdio>#include<iostream>#include<algorithm>#include<string.h>using namespace std;int c[110][110][110];int N,M;inline int lowBit(int x){    return x&(-x);}void update(int x,int y,int z,int k){    for(int i=x; i<=N; i+=lowBit(i))//三维顺序    {        for(int j=y; j<=N; j+=lowBit(j))        {            for(int l=z; l<=N; l+=lowBit(l))            {                c[i][j][l]+=k;            }        }    }}int getsum(int x,int y,int z){    int sum=0;    for(int i=x; i>0; i-=lowBit(i))    {        for(int j=y; j>0; j-=lowBit(j))        {            for(int k=z; k>0; k-=lowBit(k))            {                sum+=c[i][j][k];            }        }    }    return sum;}void UPdate(int x1,int y1,int z1,int x2,int y2,int z2){                                           //三维的区间更新            update(x2+1,y2+1,z2+1,1);//最大块    update(x1,y1,z1,5);      //最小块    update(x1,y1,z2+1,-1);//其他块    update(x1,y2+1,z1,-1);    update(x2+1,y1,z1,-1);    update(x1,y2+1,z2+1,-1);    update(x2+1,y1,z2+1,-1);    update(x2+1,y2+1,z1,-1);}int main(){    int x1,x2,y1,y2,z1,z2;    int k,ans;    while(~scanf("%d%d",&N,&M) && N && M)    {        memset(c,0,sizeof(c));        for(int i=1; i<=M; i++)        {            scanf("%d%d%d%d",&k,&x1,&y1,&z1);            if(k==0)    //单点查询            {                ans=getsum(x1,y1,z1);                printf("%d\n",ans%2);            }            else        //区间更新            {                scanf("%d%d%d",&x2,&y2,&z2);                UPdate(x1,y1,z1,x2,y2,z2);            }        }    }    return 0;}



阅读全文
0 0
原创粉丝点击