UVa 12086 Potentiometers (树状数组&点修改)

本文介绍了一种使用树状数组进行区间更新与查询的优化方法,通过具体的代码实现展示了如何高效地处理一系列更新与查询操作。这种方法特别适用于需要频繁进行区间更新和查询的问题场景。

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

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=502&page=show_problem&problem=3238


更新语句改为update(x, y - query(x, x));即可。

/*0.259s*/

const int mx = 200005;
int N, tree[mx];

void update(int p, int m)
{
	while (p <= N)
	{
		tree[p] += m;
		p += p & -p;
	}
}

int sum(int n)
{
	int sum = 0;
	while (n)
	{
		sum += tree[n];
		n -= n & -n;
	}
	return sum;
}

int query(int sta, int end) {return sum(end) - sum(sta - 1);}

#include<cstdio>
#include<cstring>

int main()
{
	//freopen("in.txt", "r", stdin);
	char ch, str[10];
	int i, x, y, tmpx, cas = 0;
	bool ok = false;
	while (scanf("%d", &N), N)
	{
		if (ok) putchar(10);
		else ok = true;
		printf("Case %d:\n", ++cas);
		memset(tree, 0, sizeof(tree));
		for (i = 1; i <= N; ++i)
		{
			scanf("%d", &x);
			update(i, x);
		}
		getchar();
		while ((ch = getchar()) != 'E')
		{
			scanf("%d%d", &x, &y);
			if (ch == 'S')
			{
				tmpx = query(x, x);
				update(x, y - tmpx);
			}
			else printf("%d\n", query(x, y));
			getchar();
		}
		gets(str);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值