hihoCoder Week 172 Matrix Sum (二维树状数组)

来源:互联网 发布:不用网络的游戏 编辑:程序博客网 时间:2024/06/05 20:20
时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

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 elementAxy. (Subscripts starts from 0

2. Sum x1 y1x2 y2: Return the sum of every elementAxy for x1xx2, y1yy2.

输入

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

输出

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

样例输入
5 8Add 0 0 1Sum 0 0 1 1Add 1 1 1Sum 0 0 1 1Add 2 2 1Add 3 3 1Add 4 4 -1Sum 0 0 4 4 
样例输出
           1
           2
           3



二维树状数组讲解:
http://blog.csdn.net/z309241990/article/details/9615259
http://blog.csdn.net/int64ago/article/details/7429868

简单的二维树状数组求区间面积:

Sum([x1,x2],[y1,y2])=query(x2,y2)+query(x1-1,y1-1)-query(x2,y1-1)-query(x1-1,y2);

这道题的取模有点坑:负数取模

#include<cstdio>#include<cstring>typedef long long ll;const int MAXN = 2000+10;#define MOD 1000000007ll c[MAXN][MAXN];int n;int lowbit(int x){return x&(-x);}void update(int x,int y,ll value){for(int i=x;i<=n;i+=lowbit(i)){for(int j=y;j<=n;j+=lowbit(j)){c[i][j]=c[i][j]+value;}}}ll query(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];}}return sum%MOD;}int main(){int m;scanf("%d%d",&n,&m);memset(c,0,sizeof(c));char str[5];while(m--){getchar();scanf("%s",str);if(str[0]=='A'){int x,y,value;scanf("%d%d%d",&x,&y,&value);x++;y++;update(x,y,value);}else{int x1,y1,x2,y2;scanf("%d%d%d%d",&x1,&y1,&x2,&y2);x1++;y1++;x2++;y2++;ll ans=query(x2,y2)+query(x1-1,y1-1)-query(x2,y1-1)-query(x1-1,y2);printf("%lld\n",(ans+MOD)%MOD);}}}


原创粉丝点击