推荐几个博客:http://www.cnblogs.com/zyf0163/p/4749042.html 树状结构之主席树
https://blog.csdn.net/creatorx/article/details/75446472 最详细的讲解,让你一次学会主席树
https://blog.csdn.net/jerans/article/details/75807666 主席树题集
https://blog.csdn.net/HTT_H/article/details/47704209 主席树入门专题
https://www.cnblogs.com/RabbitHu/p/segtree.html 递归版主席树
递归版模板大体结构:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 typedef long long ll; 6 const int maxn=5e4+10; 7 const int maxm=2e6+10; 8 int tot; 9 int c[maxm],lson[maxm],rson[maxm]; 10 int T[maxn]; 11 12 void build(int &root,int l,int r) 13 { 14 root=++tot; 15 if ( l==r ) return; 16 int mid=(l+r)/2; 17 build(lson[root],l,mid); 18 build(rson[root],mid+1,r); 19 } 20 21 void update(int root,int &rt,int p,int val,int l,int r) 22 { 23 rt=++tot; 24 lson[rt]=lson[root],rson[rt]=rson[root]; 25 c[rt]=c[root]+val; 26 if ( l==r ) return; 27 int mid=(l+r)/2; 28 if ( p<=mid ) update(lson[rt],lson[rt],p,val,l,mid); 29 else update(rson[rt],rson[rt],p,val,mid+1,r); 30 } 31 32 int query(int rt,int L,int R,int l,int r) 33 { 34 if ( L<=l && r<=R ) return c[rt]; 35 int mid=(l+r)/2; 36 int ans=0; 37 if ( L<=mid ) ans+=query(lson[rt],L,R,l,mid); 38 if ( R>mid ) ans+=query(rson[rt],L,R,mid+1,r); 39 return ans; 40 }