luoguP3834 【模板】可持久化线段树 1(主席树)
题目链接
整体二分练习题
#include<bits/stdc++.h>
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define LL long long
#define pii pair<int,int>
#define SZ(x) (int)x.size()
#define all(x) x.begin(),x.end()
using namespace std;
LL gcd(LL a, LL b) {return b ? gcd(b, a % b) : a;}
LL lcm(LL a, LL b) {return a / gcd(a, b) * b;}
LL powmod(LL a, LL b, LL MOD) {LL ans = 1; while (b) {if (b % 2)ans = ans * a % MOD; a = a * a % MOD; b /= 2;} return ans;}
const int N = 5e5 + 3;
const LL mod = 1e9 + 7;
int n,m,cnt,a[N];
LL ans[N];
struct uzi{
int o,l,r;
LL k;
int pos;
}p[N],q2[N],q1[N];
int t[N];
void add(int p,int d){
for(;p<N;p+=p&-p)t[p]+=d;
}
int get(int p){
int ans=0;
for(;p;p-=p&-p)ans+=t[p];
return ans;
}
void solve(LL x,LL y,int l,int r){
if(l>r||x>y)return ;
if(x==y){
for(int i=l;i<=r;i++)if(p[i].o==2)ans[p[i].pos]=x;//out<<p[i].l<<' '<<p[i].r<<' '<<p[i].pos<<endl;cout<<endl;
return ;
}
LL mid=x+y>>1;
int c=0,d=0;
for(int i=l;i<=r;i++){
if(p[i].o==1){
if(p[i].k<=mid)q1[++c]=p[i],add(p[i].l,p[i].r);
else q2[++d]=p[i];
}else{
int x=get(p[i].r)-get(p[i].l-1);
if(x>=p[i].k)q1[++c]=p[i];
else p[i].k-=x,q2[++d]=p[i];
}
}
for(int i=l;i<=r;i++)if(p[i].o==1&&p[i].k<=mid)add(p[i].l,-p[i].r);
for(int i=l;i<=l+c-1;i++)p[i]=q1[i-l+1];
for(int i=l+c;i<=r;i++)p[i]=q2[i-l-c+1];
solve(x,mid,l,l+c-1);
solve(mid+1,y,l+c,r);
}
int c[N];
int main() {
ios::sync_with_stdio( false);
cin>>n>>m;
for(int i=1;i<=n;i++)cin>>a[i],c[i]=a[i];
sort(c+1,c+1+n);
int len=unique(c+1,c+1+n)-c-1;
for(int i=1;i<=n;i++)a[i]=lower_bound(c+1,c+1+len,a[i])-c;
for(int i=1;i<=n;i++)p[++cnt]={1,i,1,a[i],i};
for(int i=1;i<=m;i++){
int l,r,k;
cin>>l>>r>>k;
p[++cnt]={2,l,r,k,i};
}
solve(1,len,1,cnt);
for(int i=1;i<=m;i++)cout<<c[ans[i]]<<'\n';
return 0;
}