HihoCoder1336 Matrix Sum(树状数组)

Posted caomingpei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HihoCoder1336 Matrix Sum(树状数组)相关的知识,希望对你有一定的参考价值。

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
",ans);
        }   
    }   
    
    return 0;
}

以上是关于HihoCoder1336 Matrix Sum(树状数组)的主要内容,如果未能解决你的问题,请参考以下文章

hihocoder-Week 172--Matrix Sum

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

P1336 最佳课题选择

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

线性DPlgP1336最佳课题选择

hihocoder Matrix