您的位置:首页 > 其它

HDOJ 1166 敌兵布阵(线段树单点更新求区间和)

2016-03-23 15:30 471 查看
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#define VN 50005
#define INT_MAX 0x3f3f3f3f
#define LL __int64
using namespace std;
int N, n, x, y, a, T, A[VN*3];
LL dat[VN*3];
char s[20];
void init(int n_)
{
N = 1;
while (N < n_) N *= 2;
for (int i = 0; i < 2*N-1; i++) dat[i] = 0;
}
void update(int k, int a)
{
k += N-1;
dat[k] += a;
while (k > 0)
{
k = (k - 1) / 2;
dat[k] += a;
}
}
LL query(int a, int b, int k, int l, int r)
{
if (r <= a || b <= l) return 0;
if (a <= l && r <= b) return dat[k];
else
{
LL vl = query(a, b, k*2+1, l, (l+r) / 2);
LL vr = query(a, b, k*2+2, (l+r) / 2, r);
return vl+vr;
}
}
int main()
{
scanf("%d", &T);
int cnt = 0;
while (T--)
{
printf("Case %d:\n", ++cnt);
scanf("%d", &n);
init(n);
memset(dat, 0, sizeof(dat));
for (int i = 0; i < n; i++)
{
scanf("%d", &A[i]);
update(i, A[i]);
}

while (1)
{
scanf("%s", s);
if (strcmp(s, "End") == 0) break;
if (strcmp(s, "Query") == 0)
{
scanf("%d%d", &x, &y);
LL ans = query(x-1 , y, 0, 0, N);
printf("%I64d\n", ans);
}
if (strcmp(s, "Add") == 0)
{
scanf("%d%d", &x, &a);
update(x-1, a);
}
if (strcmp(s, "Sub") == 0)
{
scanf("%d%d", &x, &a);
update(x-1, -a);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: