您的位置:首页 > 其它

uva 12086 - Potentiometers(树状数组)

2014-08-25 14:05 274 查看
题目链接:uva 12086 - Potentiometers

题目大意:给定n个整数,两个操作,
S x y:把第x个数变成y
M x y:计算第x个数到第y个数的总和

解题思路:用num数组记录每个位置上的数,每次S操作则在树状数组上的x位置加上num[x] - y的值。
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
#define lowbit(x) ((x)&(-x))
const int maxn = 200005;

int N, fenw[maxn], num[maxn];

void add (int x, int v) {
while (x <= N) {
fenw[x] += v;
x += lowbit(x);
}
}

int sum (int x) {
int ret = 0;
while (x) {
ret += fenw[x];
x -= lowbit(x);
}
return ret;
}

int main () {
int cas = 0;
while (scanf("%d", &N) == 1 && N) {
memset(fenw, 0, sizeof(fenw));
for (int i = 1; i <= N; i++) {
scanf("%d", &num[i]);
add(i, num[i]);
}

if (cas)
printf("\n");
printf("Case %d:\n", ++cas);

int x, y;
char order[15];
while (scanf("%s", order) == 1 && strcmp(order, "END")) {
scanf("%d%d", &x, &y);
if (order[0] == 'M')
printf("%d\n", sum(y) - sum(x-1));
else {
add(x, y - num[x]);
num[x] = y;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: