POJ1195 Two-dimensional tree array

Topic

Given an initial all-zero matrix, operation 1 is to add k to the element at (i, j)

Operation 2 is the sum of all elements of the output submatrix (a,b)(c,d)

Operation 3 is to end the program

2D tree array template

The only thing to note is that the title starts from 0, so add 1 to all the coordinates before proceeding.

# include<iostream>
# include<cstdio>
# include<cmath>
# include<algorithm>
const int mn = 1035;
int n;
struct Binary_tree{
int tr[mn][mn];
void add(int x,int y,int val)
{
    for(int i=x;i<=n;i+=i&-i)
        for(int j=y;j<=n;j+=j&-j)
        tr[i][j]+=val;
}
int qsum ( int x, int y)
{
    int ret=0;
   for(int i=x;i>0;i-=i&-i)
        for(int j=y;j>0;j-=j&-j)
        ret + = tr [i] [j];
    return ret;
}
}A;
intmain ()
{
   int opt,a,b,c,d;
   scanf("%d%d",&opt,&n);
   while(1)
   {
       scanf("%d",&opt);
       if(opt==3)
        break;
       else if(opt==1)
       {
           scanf("%d%d%d",&a,&b,&c);
           A.add(a+1,b+1,c);
       }
       else {
        scanf("%d%d%d%d",&a,&b,&c,&d);
        ++a,++b,++c,++d;
        printf("%d\n",A.qsum(c,d)+A.qsum(a-1,b-1)-A.qsum(c,b-1)-A.qsum(a-1,d));
       }
   }
   return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325353410&siteId=291194637