Poj-2155 Matrix //二维差分+BIT

题目链接

http://poj.org/problem?id=2155

题意

就是给一个 n n n 阶矩阵,初始时全为0,然后有 m m m 次操作,每次有两种操作:
(1) C C C x 1 x_1 x1 y 1 y_1 y1 x 2 x_2 x2 y 2 y_2 y2:将这个子矩阵内的元素全部反转( 0 0 0 1 1 1, 1 1 1 0 0 0 )
(2) Q Q Q x x x y y y :查询矩阵 ( x , y ) (x,y) (x,y) 位置处状态( 是 0 0 0还是 1 1 1 )

思路

二维差分学习博客:https://www.cnblogs.com/LMCC1108/p/10753451.html
二维树状数组学习博客:https://blog.csdn.net/weixin_43464149/article/details/99447831
二维差分经典题,可以用一个二维树状数组来维护这个二维差分数组 c [ n ] [ n ] c[n][n] c[n][n]
对于修改操作 C C C x 1 x_1 x1 y 1 y_1 y1 x 2 x_2 x2 y 2 y_2 y2 :则作以下修改:
c [ x 1 ] [ y 1 ] + = 1 c[x_1][y_1]+=1 c[x1][y1]+=1
c [ x 1 + 1 ] [ y 1 ] − = 1 c[x_1+1][y_1]-=1 c[x1+1][y1]=1
c [ x 1 ] [ y 2 + 1 ] − = 1 c[x_1][y_2+1]-=1 c[x1][y2+1]=1
c [ x 2 + 1 ] [ y 2 + 1 ] + = 1 c[x_2+1][y_2+1]+=1 c[x2+1][y2+1]+=1
对于查询操作 Q Q Q x x x y y y :直接查询前缀和即可,由于是反转操作,我们维护的是各个位置反转的次数,所以再对 2 2 2 取模即为查询结果。

参考代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int maxn=1e3+10;
const int inf=0x3f3f3f3f;
#define pb push_back
#define ft first
#define sd second
#define ms(x,y) memset(x,y,sizeof(x))
int n,m;
struct BIT{
    int bit[maxn][maxn];
    inline void init(){
        for(int i=0;i<maxn;i++){
            for(int j=0;j<maxn;j++)bit[i][j]=0;
        }
    }
    inline int lowbit(int x){ return x&(-x); }
    inline void update(int x,int y,int v){
        while(x<=n+5){
            int dy=y;
            while(dy<=n+5){
                bit[x][dy]+=v;
                dy+=lowbit(dy);
            }
            x+=lowbit(x);
        }
    }
    inline int query(int x,int y,int ans=0){
        while(x>0){
            int dy=y;
            while(dy>0){
                ans+=bit[x][dy];
                dy-=lowbit(dy);
            }
            x-=lowbit(x);
        }
        return ans;
    }
}s;
void solve(){
    cin>>n>>m;
    s.init();
    while(m--){
        char ch;int bx,by,ex,ey;
        cin>>ch;
        if(ch=='C'){
            scanf("%d%d%d%d",&bx,&by,&ex,&ey);
            s.update(bx,by,1);
            s.update(bx,ey+1,-1);
            s.update(ex+1,by,-1);
            s.update(ex+1,ey+1,1);
        }
        else {
            scanf("%d%d",&bx,&by);
            int no=s.query(bx,by);
            cout<<no%2<<'\n';
        }
    }
    printf("\n");
}
int main()
{
    int t;cin>>t;
    while(t--)solve();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值