神奇的线段树模板

两个树状数组=一棵线段树?

就是这么神奇。

本来我早就想发这个模板。。

但是忘掉了。

今天做题才想起来。。。

这是那题的AC代码。。

我干了件很逗逼的事情。

就是typedef int ll

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
#include <algorithm> 
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
typedef int ll;

struct BIT{
ll *vs;
int N;
BIT(int n){
N = n + 1;
vs = new ll[N]();
}
~BIT(){
delete[] vs;
}
void add(int k, ll a){
for (int i = k + 1; i<N; i += i&-i){
vs[i] += a;
}
}
ll sum(int s, int t){
if (s>0) return sum(0, t) - sum(0, s);
ll res = 0;
for (int i = t; i>0; i -= i&-i)
res += vs[i];
return res;
}
};
struct Seg{
BIT *dif, *pre;
Seg(int n){
dif = new BIT(n);
pre = new BIT(n);
ll *is = new ll[n];
for (int i = 0; i<n; i++){
cin >> is[i];
}
dif->add(0, is[0]);
pre->add(0, 0);
for (int i = 1; i<n; i++){
ll x = is[i] - is[i - 1];
pre->add(i, x*i);
dif->add(i, x);
}
delete[] is;
}
~Seg(){
delete dif;
delete pre;
}
void update(int s, int t, ll v){
dif->add(s, v);
dif->add(t, -v);
pre->add(s, v*s);
pre->add(t, -v*t);
}
ll query(int s, int t){
if (s>0) return query(0, t) - query(0, s);
ll ps = pre->sum(0, t);
ll ds = dif->sum(0, t);
return ds*t - ps;
}
};
void solve(int n, int m, int q){
Seg seg(n);
int l = 0;
for (int i = 0; i < q; i++){
int query;
cin >> query;
l = query - 1;
cout << seg.query(l, l + m) << 'n';
seg.update(l, l + m, -1);
}
}
int main(int agrc, char *agrv[]) {
int n, m, q;
while (cin >> n >> m >> q){
solve(n, m, q);
}
}