POJ 1195 Mobile phones

本文介绍了一种使用树状数组进行二维矩阵元素更新与范围查询的算法实现。通过树状数组,可以高效地完成矩阵中指定位置的元素值更新及指定区域的元素和查询。文章提供了完整的C++代码实现,包括树状数组的低比特位计算、求和及更新操作。

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

树状数组模板题

当n1, a[x][y]+=w;
当n
2 计算a[x1][y1]到a[x2][y2]之间矩阵的元素和
当n==3退出

#include<iostream>
#include<string.h>
#include<cstdio>
using namespace std;
typedef long long ll;
const int N = 1025;
int c[N][N]; int Row, Col;
inline int Lowbit(const int &x){// x > 0
    return x&(-x);
}
ll Sum(int i,int j){
    ll tempj, sum = 0;
    while( i > 0 ){
        tempj= j;
        while( tempj > 0 ){
            sum += c[i][tempj];
            tempj -= Lowbit(tempj);
        }
        i -= Lowbit(i);
    }
    return sum;
}
void Update(int i, int j, int num){
    int tempj;
    while( i <= Row ){
        tempj = j;
        while( tempj <= Col ){
        c[i][tempj] += num;
        tempj += Lowbit(tempj);
        }
        i += Lowbit(i);
    }
}
int main()
{
	int n,s, x1, y1, x2, y2, w;
	while(~scanf("%d%d", &n, &s))
	{
		memset(c,0,sizeof(c));  
		Row=s;
		Col=s;
		while(~scanf("%d", &n)){
		if(n==1) 
		{
			scanf("%d%d%d", &x1, &y1, &w);
			Update(x1+1,y1+1,w);  //下标不能从0开始
		}
	    else if(n==2)
		{
			scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
			printf("%lld\n", Sum(x2+1,y2+1)-Sum(x2+1,y1)-Sum(x1, y2+1)+Sum(x1, y1));
		}
		else if(n==3) break;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值