/*
Subject: Interval Tree
Author : a_clay
Created Date : 2012-02-03
Sample : hdoj 1166 敌兵布阵 很基础,很赤裸,但也很经典
*/
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
#define Bug cout << "here\n";
#define B(x) (x >> 1)
using namespace std;
const int N = 50005;
int r[N];
struct node {
int a, b;
int sum;
}t[3*N];
int SUM = 0;
void make_tree(int x, int y, int num) { // 建树
t[num].a = x;
t[num].b = y;
if(x == y) t[num].sum = r[y];
else {
make_tree(x, B(x+y), 2*num);
make_tree(B(x+y)+1, y, 2*num+1);
t[num].sum = t[2*num].sum + t[2*num+1].sum;
}
}
void add(int x, int ren, int num) {
t[num].sum += ren;
if(x == t[num].a && x == t[num].b) return;
int mid = B(t[num].a + t[num].b);
if(x <= mid) {
add(x, ren, 2*num);
}
else add(x, ren, 2*num+1);
}
void query(int x, int y, int num) {
int mid = B(t[num].a + t[num].b);
if(x <= t[num].a && t[num].b <= y) { // 找终止区间
SUM += t[num].sum;
}
else {
if(y <= mid) {
query(x, y, 2*num);
}
else if(x > mid) {
query(x, y, 2*num+1);
}
else {
query(x, y, 2*num);
query(x, y, 2*num+1);
}
}
}
int main() {
int e = 0, T, n, i;
scanf("%d", &T);
while(T--) {
memset(r, 0, sizeof(r));
memset(t, 0, sizeof(t));
cout << "Case " << ++e << ':' << endl;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &r[i]);
}
make_tree(1, n, 1);
char str[10];
int a, b;
while(cin >> str) {
if(str[0] == 'E') {
break;
}
else if(str[0] == 'A') {
cin >> a >> b;
add(a, b, 1);
}
else if(str[0] == 'S') {
cin >> a >> b;
add(a, (-b), 1);
}
else if(str[0] == 'Q') {
cin >> a >> b;
SUM = 0;
query(a, b, 1);
cout << SUM << endl;
}
}
}
return 0;
}
hdu 1166 线段树 (初步)
最新推荐文章于 2022-06-24 12:37:59 发布