POJ 2155 Matrix (two-dimensional tree array + two-dimensional difference)

Question link
: At first, a matrix of all 0s, q operations, you can modify the sub-matrix (x1, y1) to (x2, y2) to flip the elements (0 to 1, 1 to 0), and each inquiry form Point a[x1][y1]'s information.
Idea: The first reaction to this kind of interval modification is the line segment tree and the difference array, but the two-dimensional line segment tree makes no one want to type it. There is a lot of code, so for the convenience of debugging, only the difference array can be used.
I think this blog is pretty good. If you don't want to draw a picture to understand the two-dimensional difference, just look at this one. blog address

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int N=1e3+10;
int c[N][N],n,q;
inline int lowbit(int x){
    
    return x&(-x);}
void add(int x,int y,int val)
{
    
    
    int yy=y;
    while(x<=n)
    {
    
    
        yy=y;
        while(yy<=n)
        {
    
    
            c[x][yy]+=val;
            yy+=lowbit(yy);
        }
        x+=lowbit(x);
    }
}
int query(int x,int y)
{
    
    
    int res=0,yy=y;
    while(x>0)
    {
    
    
        yy=y;
        while(yy>0)
        {
    
    
            res+=c[x][yy];
            yy-=lowbit(yy);
        }
        x-=lowbit(x);
    }
    return res;
}
int main()
{
    
    
    int t;
    scanf("%d",&t);
    while(t--)
    {
    
    
        memset(c,0,sizeof(c));
        scanf("%d%d",&n,&q);
        char op[5];
        int x1,x2,y1,y2;
        for(int i=1;i<=q;i++)
        {
    
    
            scanf("%s",op);
            if(op[0]=='C')
            {
    
    
                scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
                add(x1,y1,1);
                add(x2+1,y2+1,1);
                add(x2+1,y1,-1);
                add(x1,y2+1,-1);
            }
            else
            {
    
    
                scanf("%d%d",&x1,&y1);
                printf("%d\n",query(x1,y1)%2);
            }
        }
        printf("\n");
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/amazingee/article/details/107670297