F - Matrix Sum HihoCoder - 1336

題目:

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.

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 ≤ x1 ≤ x2 < N, 0 ≤ y1 ≤ y2 < 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

題目大意:給你一個N*N二維矩陣,初始值時都爲0,有兩種操作

1:單點修改值
2:給出一個子矩陣的左上和右下角的座標,詢問一個子矩形範圍內的值的和.

二維樹狀數組模板題,單點更新區間詢問

代碼:

#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 = 1000000000;
const int maxn = 1234;
const int mod = 1e9+7;
int T,n,m;
char op[4];
int sx,sy,ex,ey;
int c[maxn][maxn];

int lowbit(int x)
{
    return x&(-x);
}

ll query_sum(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])%mod;
        }
    }
    return sum;
}

void update(int x,int y,int v)
{
    for(int i=x;i<maxn;i+=lowbit(i))
    {
        for(int j=y;j<maxn;j+=lowbit(j))
        {
            c[i][j]=(c[i][j]+v)%mod;
        }
    }
}

int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(c,0,sizeof(c));
        int a,b,w;
        while(m--)
        {
            scanf("%s",op);
            if(op[0]=='A')
            {
                scanf("%d%d%d",&a,&b,&w);
                a++,b++;
                update(a,b,w);
            }
            else
            {
                scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
                sx++,sy++,ex++,ey++;
                printf("%lld\n",(query_sum(ex,ey)-query_sum(sx-1,ey)-query_sum(ex,sy-1)+query_sum(sx-1,sy-1)+mod)%mod);
            }
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章