hihocoder1336-Matrix Sum(二维树状数组)

来源:互联网 发布:矩阵乘法 matlab 编辑:程序博客网 时间:2024/06/05 16:34

1336 : Matrix Sum

时间限制: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 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.

输入
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

题意:

要维护矩形单点修改,矩形区间求和
二维树状数组模板题
模拟即可

#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>using namespace std;typedef long long LL;const int maxn=1000+5,maxm=1e5+5;const LL mod=1e9+7;LL T[maxn][maxn];int n,m;char opt[6];inline LL get(int x,int y){  LL res=0;  for(int i=x;i;i-=i&-i)    for(int j=y;j;j-=j&-j)      res=(res+T[i][j])%mod;  return res;}inline void add(int x,int y,int z){  for(int i=x;i<=n;i+=i&-i)    for(int j=y;j<=n;j+=j&-j)      T[i][j]=(T[i][j]+z)%mod;}int main(){  while(~scanf("%d%d",&n,&m))  {    int x,y,x1,y1;    LL z;    memset(T,0,sizeof(T));    for(int i=1;i<=m;++i)    {      scanf("%s%d%d",opt,&x,&y);      x++,y++;      if(opt[0]=='A')      {        scanf("%lld",&z);        add(x,y,z);      }      else      {        scanf("%d%d",&x1,&y1);        x1++,y1++;        printf("%lld\n",((get(x1,y1)-get(x-1,y1)-get(x1,y-1)+get(x-1,y-1))%mod+mod)%mod);      }    }  }  return 0;}
原创粉丝点击