-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathP12086.cpp
93 lines (87 loc) · 1.93 KB
/
P12086.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
struct Node {
int low, high, val;
};
Node *tree;
int read(int low, int high, int nodeI) {
Node &n = tree[nodeI];
if(n.low > high || n.high < low)
return 0;
if(n.low >= low && n.high <= high)
return n.val;
return read(low, high, nodeI*2+1) + read(low, high, nodeI*2+2);
}
int main() {
int N;
for(int cas = 1; true; ++cas) {
cin >> N;
if(N == 0)
return 0;
if(cas != 1)
cout << endl;
cout << "Case " << cas << ":" << endl;
// Build tree:
tree = new Node[4*N];
int rowSize = 1;
int rowIdx = 0;
while(rowSize < N) {
rowIdx += rowSize;
rowSize <<= 1;
}
// Read data and set tree info:
FORI(rowSize) { // Insert all leafs and bump data up the tree:
int nodeI = rowIdx + i;
if(i >= N)
tree[nodeI].val = 0;
else
cin >> tree[nodeI].val;
tree[nodeI].low = tree[nodeI].high = i;
// Bump data up as long as we are at a right child:
int parentI;
while(((parentI = (nodeI-1)/2)*2+2) == nodeI) { // while we are the right child:
tree[parentI].low = tree[nodeI-1].low;
tree[parentI].high = tree[nodeI].high;
tree[parentI].val = tree[nodeI].val + tree[nodeI-1].val;
nodeI = parentI;
if(nodeI == 0)
break; // root
}
} // FORI
// Handle queries:
string s;
bool done = false;
while(!done) {
cin >> s;
switch(s[0]) {
case 'S': // Update tree:
{
int i; cin >> i; --i;
int nodeI = rowIdx + i;
int oldVal = tree[nodeI].val;
cin >> tree[nodeI].val;
int diff = tree[nodeI].val - oldVal;
// Bump data up:
while(true) {
int parentI = (nodeI-1)/2;
tree[parentI].val += diff;
nodeI = parentI;
if(nodeI == 0)
break; // root
}
}
break;
case 'M':
{
int low, high; cin >> low >> high; --low; --high;
cout << read(low, high, 0) << endl;
}
break;
case 'E':
done = true;
break;
default:
die();
}
}
delete[] tree;
}
}