二维树状数组 区间求和模板(#1336 : 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 ≤ x2y1 ≤ 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 <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;
const int ma=1100;
int mod=1e9+7;
int n,m;
int c[ma][ma];
int a[ma][ma];

int lowbit(int x)
{
    return x&(-x);
}
void add(int x,int y,int v)
{
    for(int i=x;i<=1010;i+=lowbit(i))
    {
        for(int j=y;j<=1010;j+=lowbit(j))
        c[i][j]+=v;

    }
}

long long sum(int x,int y)
{
    long long su=0;
    for(int i=x;i>0;i-=lowbit(i))
    {
        for(int j=y;j>0;j-=lowbit(j))
        su=(c[i][j]+su)%mod;

    }
    return su;
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        memset(c,0,sizeof(c));
        memset(a,0,sizeof(a));
        while(m--)
        {
             char p[4];
             scanf("%s",p);
             if(p[0]=='A')
             {
                 int w1,w2,e1;
                  scanf("%d%d%d",&w1,&w2,&e1);
                  w1++;w2++;
                  add(w1,w2,e1);
                  a[w1][w2]=(e1+a[w1][w2])%mod;

             }
             else if(p[0]=='S')
             {
                 int r1,r2,w1,w2;
                 scanf("%d%d%d%d",&r1,&r2,&w1,&w2);
                 r1++;r2++;w1++;w2++;
                 if(r1>w1)swap(r1,w1);
                 if(r2>w2)swap(r2,w2);
                 int sun=0;
                 sun=sum(w1,w2)-sum(w1,r2-1)-sum(r1-1,w2)+sum(r1-1,r2-1);
                 while(sun<0)sun+=mod;
                 printf("%d\n",sun);
             }
             }

        }
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值