-
Notifications
You must be signed in to change notification settings - Fork 11
/
SPOJ1029.cc
65 lines (60 loc) · 1.48 KB
/
SPOJ1029.cc
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
// SPOJ 1029: Matrix Summation
// http://www.spoj.com/problems/MATSUM/
//
// Solution: 2D fenwick tree
#include <iostream>
#include <vector>
#include <cstdio>
#include <algorithm>
using namespace std;
#define fst first
#define snd second
#define all(c) ((c).begin()), ((c).end())
template <class T>
struct fenwick_tree_2d {
vector<vector<T>> x;
fenwick_tree_2d(int n, int m) : x(n, vector<T>(m)) { }
void add(int k1, int k2, int a) { // x[k] += a
for (; k1 < x.size(); k1 |= k1+1)
for (int k=k2; k < x[k1].size(); k |= k+1) x[k1][k] += a;
}
T sum(int k1, int k2) { // return x[0] + ... + x[k]
T s = 0;
for (; k1 >= 0; k1 = (k1&(k1+1))-1)
for (int k=k2; k >= 0; k = (k&(k+1))-1) s += x[k1][k];
return s;
}
};
void doit() {
int n; scanf("%d", &n);
fenwick_tree_2d<int> FT(n,n);
while (1) {
char cmd[5];
scanf("%s", cmd);
switch (cmd[1]) {
case 'E': {
int i, j, a;
scanf("%d %d %d", &i, &j, &a);
int b = FT.sum(i, j) + FT.sum(i-1,j-1) - FT.sum(i-1,j) - FT.sum(i,j-1);
FT.add(i, j, a - b);
}
break;
case 'U': {
int i, j, k, l;
scanf("%d %d %d %d", &i, &j, &k, &l);
int b = FT.sum(k, l) + FT.sum(i-1,j-1) - FT.sum(i-1,l) - FT.sum(k,j-1);
printf("%d\n", b);
break;
}
case 'N': {
printf("\n");
return;
}
}
}
}
int main() {
int cases;
scanf("%d", &cases);
for (int icases = 0; icases < cases; ++icases) doit();
}