首页 > 代码库 > 主席树模板

主席树模板

#include<bits/stdc++.h>
using namespace std;
#ifdef ONLINE_JUDGE
char *TT,*mo,but[(1<<15)+2];
#define getchar() ((TT==mo&&(mo=(TT=but)+fread(but,1,1<<15,stdin)),TT==mo)?0:*TT++)
#endif
inline int read(){
    int x=0,c=0,f=1;
    for(;c<‘0‘||c>‘9‘;c=getchar())f=c!=‘-‘;
    for(;c>=‘0‘&&c<=‘9‘;c=getchar())x=x*10+c-‘0‘;
    return f?x:-x;
} 
#define mid (L+R>>1)
const int N=500011;
struct tree{int sum;tree *ls,*rs;}pool[N*20],*num=pool,*rt[N];
void build(tree *&o){o=num++;o->ls=o->rs=o;}
 
void update(tree *&o,tree *x,int L,int R,int v){
    o=num++;o->sum=x->sum+1;
    if(L==R)return ;
    o->ls=x->ls,o->rs=x->rs;
    if(v<=mid)update(o->ls,x->ls,L,mid,v);
    else update(o->rs,x->rs,mid+1,R,v);
}
int query(tree *a,tree *b,int L,int R,int x){
    if(b->sum-a->sum<x)return 0;
    if(L==R)return b->sum-a->sum>x?L:0;
    if(b->ls->sum-a->ls->sum>x)return query(a->ls,b->ls,L,mid,x);
    else return query(a->rs,b->rs,mid+1,R,x);
}
int n,sz,a[N];
int main(){
    n=read();int q=read();
    for(int i=1;i<=n;i++)a[i]=read();
    build(rt[0]);
    for(int i=1;i<=n;i++)update(rt[i],rt[i-1],1,n,a[i]);
    while(q--){
        int l=read(),r=read();
        printf("%d\n",query(rt[l-1],rt[r],1,n,(r-l+1)>>1));
    }
}

  

这个已经背下来了

主席树模板