(HihoCoder

来源:互联网 发布:淘宝晚上收货时间 编辑:程序博客网 时间:2024/05/17 08:36

(HihoCoder - 1336)Matrix Sum

You are given an N × N matrix. At the beginning every element is 0. Write a program supporting 2 operations:

  1. Add x y value: Add value to the element Axy. (Subscripts starts from 0

    1. Sum x1 y1 x2 y1: Return the sum of every element Axy for x1 ≤ x ≤ x2, y1 ≤ y ≤ y2.

Input

The first line contains 2 integers N and M, the size of the matrix and the number of operations.

Each of the following M line contains an operation.

1 ≤ N ≤ 1000, 1 ≤ M ≤ 100000

For each Add operation: 0 ≤ x < N, 0 ≤ y < N, -1000000 ≤ value ≤ 1000000

For each Sum operation: 0 ≤ x1 ≤ x2 < N, 0 ≤ y1 ≤ y2 < N

Output

For each Sum operation output a non-negative number denoting the sum modulo 109+7.

Sample Input

5 8
Add 0 0 1
Sum 0 0 1 1
Add 1 1 1
Sum 0 0 1 1
Add 2 2 1
Add 3 3 1
Add 4 4 -1
Sum 0 0 4 4

Sample Output

1
2
3

题目大意:对于一个n*n的二维数组,对其进行m次操作,add x y v 指在(x,y)处加v,sum x1 y1 x2 y2 询问在左下角为(x1,y1)右上角为(x2,y2)的矩形里面元素的和。

思路:二维树状数组模板里,用二维数组数组来维护这一系列操作。

#include<cstdio>#include<cstring>using namespace std;typedef long long LL;const LL mod=1e9+7;const int maxn=1005;LL c[maxn][maxn];char op[5];int lowbit(int x){    return x&-x;}void update(int x,int y,int d){    for(int i=x;i<maxn;i+=lowbit(i))        for(int j=y;j<maxn;j+=lowbit(j)) c[i][j]=(c[i][j]+d)%mod;}LL getsum(int x,int y){    LL sum=0;    for(int i=x;i>0;i-=lowbit(i))        for(int j=y;j>0;j-=lowbit(j)) sum=(sum+c[i][j])%mod;    return sum;}int main(){    int n,m;    while(~scanf("%d%d",&n,&m))    {        memset(c,0,sizeof(c));        while(m--)        {            scanf("%s",op);            if(op[0]=='A')            {                int x,y,v;                scanf("%d%d%d",&x,&y,&v);                x++,y++;                update(x,y,v);//+1的目的是为了排除0而避免死循环             }            else            {                int x1,y1,x2,y2;                scanf("%d%d%d%d",&x1,&y1,&x2,&y2);                x1++,y1++,x2++,y2++;                LL ans=((getsum(x2,y2)-getsum(x1-1,y2)-getsum(x2,y1-1)+getsum(x1-1,y1-1))%mod+mod)%mod;                printf("%lld\n",ans);            }        }    }    return 0;}
原创粉丝点击