POJ2155 Matrix 题解(树状数组)

题目:POJ2155.
题目大意:对一个 n ∗ n n*n nn的矩阵支持:
1.格式 C   x 1   y 1   x 2   y 2 C\,x1\,y1\,x2\,y2 Cx1y1x2y2,表示将左上角为 ( x 1 , y 1 ) (x1,y1) (x1,y1),右下角为 ( x 2 , y 2 ) (x2,y2) (x2,y2)的矩阵全部取反,即 0 0 0 1 1 1 1 1 1 0 0 0.
2.格式 Q   x   y Q\,x\,y Qxy,表示查询位置 ( x , y ) (x,y) (x,y)的值.
设询问次数为 t t t,则 1 ≤ n ≤ 1 0 3 , 1 ≤ t ≤ 5 ∗ 1 0 4 1\leq n\leq 10^3,1\leq t\leq 5*10^4 1n103,1t5104,数据组数 ≤ 10 \leq 10 10.

二维树状数组裸题,我们直接把原来一维的数组扩展成二维的,在写修改和查询时改成两重循环就可以了,时间复杂度变为 O ( l o g 2 n ) O(log^2n) O(log2n)一次操作.

代码如下:

//#include
#include
#include
#include
  using namespace std;
#define Abigail inline void
#define rep(i,j,k) for (int i=j;i<=k;i++)
typedef long long LL;
const int N=1000;
const int INF=(1<<30)-1+(1<<30);
int a[N+9][N+9],n,q;
int lowbit(int x){
  return x&-x;
}
void change(int x,int y){
  for (int i=x;i<=n;i+=lowbit(i))
    for (int j=y;j<=n;j+=lowbit(j))
      a[i][j]^=1;
}
int query(int x,int y){
  int sum=0;
  for (int i=x;i>0;i-=lowbit(i))
    for (int j=y;j>0;j-=lowbit(j))
      sum^=a[i][j];
  return sum;
}
void rc(char &c){
  c=getchar();
  while (c<'A'||c>'Z') c=getchar();
}
Abigail into(){
  memset(a,0,sizeof(a));
  scanf("%d%d",&n,&q);
}
Abigail work(){
  char c;
  int x1,y1,x2,y2;
  for (int i=1;i<=q;i++){
    rc(c);
    if (c=='C'){
      scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
      change(x1,y1);change(x1,y2+1);change(x2+1,y1);change(x2+1,y2+1);
    }else{
      scanf("%d%d",&x1,&y1);
      printf("%d\n",query(x1,y1));
    }
  }
  printf("\n");
}
Abigail outo(){
}
int main(){
  int T=0;
  scanf("%d",&T);
  while (T--){
    into();
    work();
    outo();
  }
  return 0;
}

你可能感兴趣的:(POJ2155 Matrix 题解(树状数组))