HihoCoder1336 Matrix Sum(樹狀數組)
阿新 • • 發佈:2018-08-22
you 輸出 val ostream ace sin const begin 二維數組
HihoCoder1336 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 y2: Return the sum of every element Axy for x1 ≤ x ≤ x2, y1 ≤ y ≤ y2.
輸入
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
輸出
For each Sum operation output a non-negative number denoting the sum modulo 109+7.
樣例輸入
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
樣例輸出
1
2
3
題解
題意
查詢、修改二維數組中的相關值。
思路
二維樹狀數組維護所有操作,二維樹狀數組的相關操作與一維幾乎完全相同。
代碼
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<string> #include<vector> #include<stack> #include<bitset> #include<cstdlib> #include<cmath> #include<set> #include<list> #include<deque> #include<map> #include<queue> using namespace std; typedef long long ll; const double PI = acos(-1.0); const double eps = 1e-6; const int INF = 0x3f3f3f3f; #define REP(i,n) for(int i=0;i<(n);i++) const int MAXN = 1000+10; const int MAXM = 10000+10; int A[MAXN][MAXM]; int N,M; const int MOD = 1e9+7; void init(){ memset(A,0,sizeof(A)); } int lowbit(int x){ return x&(-x); } ll getsum(int x,int y){ ll ans =0; for(int i=x;i>=1;i-=lowbit(i)){ for(int j=y;j>=1;j-=lowbit(j)){ ans += A[i][j]; ans%=MOD; } } return ans; } int add(int x,int y,int val){ for(int i=x;i<=N;i+=lowbit(i)){ for(int j=y;j<=M;j+=lowbit(j)){ A[i][j]+=val; } } return 0; } ll mysum(int x1,int y1,int x2,int y2){ ll ans=getsum(x2,y2)-getsum(x1-1,y2)-getsum(x2,y1-1)+getsum(x1-1,y1-1); while(ans<0) ans+=MOD; return ans; } int main(){ init(); scanf("%d %d",&N,&M); char str[20]; while(~scanf("%s",str)){ if(str[0]=='A'){ int a,b,v; scanf("%d %d %d",&a,&b,&v); add(a+1,b+1,v); }else{ int x1,y1,x2,y2; scanf("%d %d %d %d",&x1,&y1,&x2,&y2); ll ans = mysum(x1+1,y1+1,x2+1,y2+1); printf("%lld\n",ans); } } return 0; }
HihoCoder1336 Matrix Sum(樹狀數組)