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

2. Sum x1 y1 x2 y1: Return the sum of every element Axy for x1xx2, y1yy2.

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 ≤ x1x2 < N, 0 ≤ y1y2 < 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 
二维的树状数组,做法与一维类似,注意求区间时加减范围。
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 
 6 using namespace std;
 7 
 8 const int maxn=1005;
 9 int g[maxn][maxn],n;
10 
11 void update(int x,int y,int v)
12 {
13     int j=y;
14     for(;x<=n;x+=x&(-x))
15         for(y=j;y<=n;y+=y&(-y))
16         {
17             g[x][y]+=v;
18             g[x][y]%=1000000007;
19         }
20 }
21 
22 long long getsum(int x,int y)
23 {
24     long long sum=0;
25     int j=y;
26     for(;x>0;x-=x&(-x))
27         for(y=j;y>0;y-=y&(-y))
28         {
29             sum+=g[x][y];
30             sum%=1000000007;    
31         }
32     return sum;
33 }
34 
35 int main()
36 {
37     int m,x1,y1,x2,y2,v;
38     while(~scanf("%d%d",&n,&m))
39     {
40         memset(g,0,sizeof(g));
41         char s[5];
42         for(int i=0;i<m;i++)
43         {
44             cin>>s;
45             if(s[0]=='A')
46             {
47                 scanf("%d%d%d",&x1,&y1,&v);
48                 update(x1+1,y1+1,v);
49             }
50             else
51             {
52                 scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
53                 long long ans=0;
54                 ans+=getsum(x2+1,y2+1)%(1000000007);
55                 ans-=getsum(x1,y2+1)%(1000000007);
56                 ans-=getsum(x2+1,y1)%(1000000007);
57                 ans+=getsum(x1,y1)%(1000000007);
58                 ans%=1000000007;
59                 if(ans<0)
60                     ans+=1000000007;
61                 printf("%lld\n",ans);
62             }
63         }    
64     }
65     
66     
67     return 0;    
68 } 

 

posted @ 2017-08-16 08:24  西北会法语  阅读(135)  评论(0编辑  收藏  举报