HihoCoder - 1336 Matrix Sum

Posted 西北会法语

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 } 

 

以上是关于HihoCoder - 1336 Matrix Sum的主要内容,如果未能解决你的问题,请参考以下文章

HihoCoder - 1336 二维数状数组(单点更新 区间查询)

hihocoder-Week 172--Matrix Sum

P1336 最佳课题选择

luogu P1336 最佳课题选择 |背包dp

线性DPlgP1336最佳课题选择

hihocoder Matrix