二维树状数组

#include<iostream>
#include<cstdio>
#include<math.h>
#include<bits/stdc++.h>
//#define y1 y11
using namespace std;
const int maxn=1e3+10;
int lowbit(int x){return x&(-x); }
int a[maxn][maxn];
int b[maxn][maxn];
int n=1e3+9;
void update(int x,int y,int p)
{
    for(int i=x;i<n;i=i+lowbit(i))
        for(int j=y;j<n;j=j+lowbit(j))
           a[i][j]+=p;
 }
int getsum(int x,int y)
{
    int sum=0;
    for(int i=x;i>0;i=i-lowbit(i))
        for(int j=y;j>0;j=j-lowbit(j))
           sum+=a[i][j];
    return sum;
}
int main()
{
    int T; scanf("%d",&T);
    while(T--)
    {//getchar();
        char ss[10];   scanf("%s",ss);
        if(ss[0]=='Q')
        {
            int x11,x22,y11,y22;scanf("%d %d %d %d",&x11,&x22,&y11,&y22); x11++; x22++;y11++; y22++;
            if(x11>x22) swap(x11,x22);
            if(y11>y22) swap(y11,y22);

            printf("%d
",getsum(x22,y22)+getsum(x11-1,y11-1)-getsum(x22,y11-1)-getsum(x11-1,y22));
        }
        else
        {
            int x,y; scanf("%d %d",&x,&y); x++;y++;
            if(ss[0]=='B')
            {
                if(b[x][y]==1) continue;
                update(x,y,1);
                b[x][y]=1;
            }
            if(ss[0]=='D')
            {
                if(b[x][y]==0) continue;
                update(x,y,-1);
                b[x][y]=0;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/Andromeda-Galaxy/p/10299510.html