您的位置:首页 > 其它

hdu1166敌兵布阵(大意)树状数组

2014-07-25 13:59 288 查看
//http://acm.hdu.edu.cn/showproblem.php?pid=1166

大意:给你一串数,然后会根据题意选择一点增加或减少,或者询问某区间的人数有多少?之前用线段树写了,而这题可以用树状树状来做,更加方便更加快速。

说下树状数组的三个主要函数:

#include<iostream>
using namespace std;
#define lowbit(x) (x)&(-x)
int N;
int c[50005];
//更新整个树状数组
void update(int pos, int value)
{
while (pos <= N)
{
c[pos] += value;
pos += lowbit(pos);
}
}
//查询前pos项和
int query(int pos)
{
int sum = 0;
while (pos > 0)
{
sum += c[pos];
pos -= lowbit(pos);
}
return sum;
}
int main()
{
int cas;
int t = 1;
scanf("%d", &cas);
while (cas--)
{
printf("Case %d:\n", t++);
int temp;
scanf("%d", &N);
memset(c, 0, sizeof(c));
for (int i = 1; i <= N; i++)
{
scanf("%d", &temp);
update(i, temp);
}
char str[10];
while (scanf("%s", str) != EOF)
{
if (str[0] == 'E')
break;
int a, b;
scanf("%d%d", &a, &b);
if (str[0] == 'A')
{
update(a, b);
}
else if (str[0] == 'S')
{
update(a, -b);
}
else
{
printf("%d\n", query(b) - query(a - 1));
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息