关键词:主席树 相关题目:[JSOI2018]军训列队

题面

AC代码

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
#include <cstdio>
#include <cctype>
#define re register int
#define rep(i,a,b) for(re i=(a);i<=(b);++i)
const int N = 500020, MAXN = 1500000;
int n, m, id=0;
int ls[N*50], rs[N*50], siz[N*50], root[N];
long long sum[N*50];

inline void read(int &x) {
x=0;
int f=1;char ch=getchar();
while (!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while (isdigit(ch)){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
x*=f;
}

inline long long getsum(int l, int r) { return 1ll*(l+r)*(r-l+1)/2;}

void add(int &now, int nxt, int l, int r, int z) {
now = ++id;
ls[now] = ls[nxt], rs[now] = rs[nxt];
siz[now] = siz[nxt]+1, sum[now] = sum[nxt]+z;
if(l==r) return ;

int mid = (l+r)>>1;
if(z <= mid) add(ls[now], ls[nxt], l, mid, z);
else add(rs[now], rs[nxt], mid+1, r, z);
}

int main() {
read(n), read(m);
int p;
rep(i,1,n) {
read(p);
add(root[i], root[i-1], 1, MAXN, p);
}

int l, r, ld, rd, mid, L, R, now, nxt, size, tot;
long long lsum, rsum;
while(m--) {
read(l), read(r), read(L); R = L+r-l;
now = root[r], nxt = root[l-1];
tot = lsum = rsum = 0;
ld = 1, rd = MAXN;
while(ld < rd) {
mid = (ld+rd)>>1;
size = siz[ls[now]]-siz[ls[nxt]];
if(size+tot >= mid-L+1) {
tot += size, ld = mid+1, lsum += sum[ls[now]]-sum[ls[nxt]];
nxt = rs[nxt], now = rs[now];
}
else {
rd = mid, rsum += sum[rs[now]]-sum[rs[nxt]];
nxt = ls[nxt], now = ls[now];
}
}
if(ld < L)
printf("%lld\n", rsum-getsum(L, R));
else if(ld > R)
printf("%lld\n", getsum(L, R)-lsum);
else
printf("%lld\n", getsum(L, ld-1)-lsum+rsum-getsum(ld, R));
}
}