题解
老年选手一道裸的主席树都要看好久才看出来
首先熟练的把这个区间建成(n)个主席树
然后对于一个询问,我们相当于在主席树上二分一个mid,使得(mid - K + 1)正好和([l,r])区间中坐标在([1,mid])的人数一样就好
(居然代码只有2.2K,似乎比平均码长低啊,开心)
代码
#include <bits/stdc++.h>
#define fi first
#define se second
#define pii pair<int,int>
#define pdi pair<db,int>
#define mp make_pair
#define pb push_back
#define enter putchar('
')
#define space putchar(' ')
#define MAXN 500005
#define eps 1e-8
//#define ivorysi
using namespace std;
typedef long long int64;
typedef double db;
template<class T>
void read(T &res) {
res = 0;char c = getchar();T f = 1;
while(c < '0' || c > '9') {
if(c == '-') f = -1;
c = getchar();
}
while(c >= '0' && c <= '9') {
res = res * 10 + c - '0';
c = getchar();
}
res *= f;
}
template<class T>
void out(T x) {
if(x < 0) {x = -x;putchar('-');}
if(x >= 10) {
out(x / 10);
}
putchar('0' + x % 10);
}
const int MAXV = 2000000;
struct node {
int lc,rc;
int64 sum,cnt;
}tr[MAXN * 22];
int N,M;
int a[MAXN],rt[MAXN],Ncnt;
int64 f(int l,int r) {
return 1LL * (l + r) * (r - l + 1) / 2;
}
void Insert(const int &x,int &y,int L,int R,int v) {
y = ++Ncnt;
tr[y] = tr[x];
tr[y].sum += v;tr[y].cnt++;
if(L == R) return;
int mid = (L + R) >> 1;
if(v <= mid) Insert(tr[x].lc,tr[y].lc,L,mid,v);
else Insert(tr[x].rc,tr[y].rc,mid + 1,R,v);
}
pair<int64,int64> Query(int x,int y,int L,int R,int K,int len) {
pair<int64,int64> res = mp(0,0);
while(L <= R) {
if(L == R) {
res.fi += tr[y].sum - tr[x].sum;
res.se += tr[y].cnt - tr[x].cnt;
break;
}
pair<int64,int64> t = res;
int mid = (L + R) >> 1;
t.fi += tr[tr[y].lc].sum - tr[tr[x].lc].sum;
t.se += tr[tr[y].lc].cnt - tr[tr[x].lc].cnt;
if(mid >= K && mid - K + 1 >= t.se) {
R = mid;
x = tr[x].lc;y = tr[y].lc;
}
else {
L = mid + 1;
res = t;
x = tr[x].rc;y = tr[y].rc;
}
}
return res;
}
void Solve() {
read(N);read(M);
for(int i = 1 ; i <= N ; ++i) read(a[i]);
for(int i = 1 ; i <= N ; ++i) {
Insert(rt[i - 1],rt[i],1,MAXV,a[i]);
}
int l,r,K;
for(int i = 1 ; i <= M ; ++i) {
read(l);read(r);read(K);
pair<int64,int64> t;
t = Query(rt[l - 1],rt[r],1,MAXV,K,r - l + 1);
int64 ans = f(K,K + t.se - 1) - f(K + t.se,K + r - l);
ans -= t.fi;
ans += tr[rt[r]].sum - tr[rt[l - 1]].sum - t.fi;
out(ans);enter;
}
}
int main() {
#ifdef ivorysi
freopen("f1.in","r",stdin);
#endif
Solve();
}