`

hdu 3584 Cube(三维树状数组)

阅读更多

Cube

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 660    Accepted Submission(s): 309

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 5 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 2 2 2 0 1 1 1 0 2 2 2

 

Sample Output
1 0 1
 
       不想多说,这题就是poj2155 Matrix基本一样,不过这个三维而已,原理一模一样,树状数组轻松解决。
代码:
#include <iostream>
#include <stdio.h>
#include <memory.h>
using namespace std;

int a[105][105][105], n;

int lowbit(int i)
{
    return i&(-i);
}

void update(int i, int j, int k, int x) //三维树状数组更新
{
    int tj, tk;
    while(i <= n)
    {
        tj = j;
        while(tj <= n)
        {
            tk = k;
            while(tk <= n)
            {
                a[i][tj][tk] += x;
                tk += lowbit(tk);
            }
            tj += lowbit(tj);
        }
        i += lowbit(i);
    }
}

int sum(int i, int j, int k)    //三维树状数组求和
{
    int tj, tk, sum = 0;
    while(i > 0)
    {
        tj = j;
        while(tj > 0)
        {
            tk = k;
            while(tk > 0)
            {
                sum += a[i][tj][tk];
                tk -= lowbit(tk);
            }
            tj -= lowbit(tj);
        }
        i -= lowbit(i);
    }
    return sum;
}

int main()
{
    int t, k;
    int x1, y1, z1, x2, y2, z2;
    while(scanf("%d %d", &n, &t) != EOF)
    {
        memset(a, 0, sizeof(a));
        while(t--)
        {
            scanf("%d", &k);
            if(k == 0)
            {
                scanf("%d%d%d", &x1, &y1, &z1);
                printf("%d\n", sum(x1, y1, z1)&1);
            }
            else if(k == 1)
            {
                scanf("%d%d%d%d%d%d", &x1, &y1, &z1, &x2, &y2, &z2);
                ///三维树状数组更新-容斥原理
                update(x2+1, y2+1, z2+1, 1);
                update(x1, y2+1, z2+1, 1);
                update(x2+1, y1, z2+1, 1);
                update(x2+1, y2+1, z1, 1);
                update(x1, y1, z2+1, 1);
                update(x2+1, y1, z1, 1);
                update(x1, y2+1, z1, 1);
                update(x1, y1, z1, 1);
            }
        }
    }

    return 0;
}
 
2
4
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics