hihocode 1336 Matrix Sum 【二维树状数组】

本文介绍了一种处理二维数列的算法,该算法能够高效地执行两种操作:一是更新指定位置的数值;二是求解特定子矩阵内所有元素之和,并通过取模确保结果的有效范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

两个操作:

 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.

注意取模,因为value可能为负值

        ans%=Mod;
       if(ans<0) ans+=Mod;

#include <iostream>
#include <cstdio>

using namespace std;
const int Max = 1010;
const int Mod = 1e9+7;
typedef long long LL;
int n;
int c[1010][1010];

int lowbit(int x)
{
    return x&(-x);
}
void update(int x,int y,int val)
{
    for(int i=x;i<=Max;i+=lowbit(i))
    {
        for(int j=y;j<=Max;j+=lowbit(j))
        {
            c[i][j]+=val;
        }
    }
}
LL sum(int x,int y)
{
    LL res = 0;
   for(int i=x;i>0;i-=lowbit(i))
    for(int j=y;j>0;j-=lowbit(j))
        res += c[i][j];
   return res;
}
int main()
{
    int op,x,y,X,Y,val;
    string str;
    scanf("%d%d",&n,&op);
    while(op--)
    {
        cin>>str;
        if(str[0]=='A'){
            scanf("%d%d%d",&x,&y,&val);
            x++,y++;
            update(x,y,val);
        }else{//sum
            scanf("%d%d%d%d",&x,&y,&X,&Y);
            x++,y++,X++,Y++;

            LL ans =sum(X,Y)+sum(x-1,y-1)-sum(X,y-1)-sum(x-1,Y);
            ans%=Mod;
            if(ans<0) ans+=Mod;
            printf("%d\n",ans);
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值