SPOJ1029 - Matrix Summation

题目大意

给定一个N*N的矩阵A,每个元素的初始值为0,可以对矩阵进行一下两种操作:

1、修改A[i][j]的值为d,(1<=i,j<=N)

2、查询左下角坐标为(x1,y1),右上角坐标为(x2,y2)的子矩阵的元素和

题解

基本的树状数组,单点增减,区间求和

#include<iostream>

#include<cstring>

#include<cstdio>

#define MAXN 1050

using namespace std;

int n;

int c[MAXN][MAXN],a[MAXN][MAXN];

int lowbit(int x)

{

    return x&-x;

}

void add(int x,int y,int d)

{

    int i,j;

    for(i=x;i<=MAXN;i+=lowbit(i))

    for(j=y;j<=MAXN;j+=lowbit(j))

    c[i][j]+=d;

}

int sum(int x,int y)

{

    int ret=0,i,j;

    for(i=x;i>0;i-=lowbit(i))

    for(j=y;j>0;j-=lowbit(j))

        ret+=c[i][j];

    return ret;

}

int main()

{

    int T,x1,x2,y1,y2,ans,t;

    char s[5];

    scanf("%d",&T);

    while(T--)

    {

        memset(c,0,sizeof(c));

        memset(a,0,sizeof(a));

         scanf("%d",&n);

         while(scanf("%s",s)!=EOF)

         {

             if(s[0]=='E') break;

             if(s[2]=='T')

             {

                 scanf("%d%d%d",&x1,&y1,&t);

                 x1++;

                 y1++;

                 add(x1,y1,t-a[x1][y1]);

                 a[x1][y1]=t;

             }

             else

             {

                 scanf("%d%d%d%d",&x1,&y1,&x2,&y2);

                 x1++;

                 y1++;

                 x2++;

                 y2++;

                 ans=sum(x2,y2)-sum(x1-1,y2)-sum(x2,y1-1)+sum(x1-1,y1-1);

                 printf("%d\n",ans);

             }

         }

    }

    return 0;

}

你可能感兴趣的:(Matrix)