主席树-查询区间有多少个不同的数
2017-08-11 19:33
417 查看
#include<iostream> #include<cstdio> #include<algorithm> #include<map> #include<cstring> using namespace std; const int MAXN=3e4+5; const int M=MAXN*100; int n,q,tot; int a[MAXN]; int T[MAXN],lson[M],rson[M],c[M]; int build(int l,int r) { int root=tot++; c[root]=0; if(l!=r) { int mid=(l+r)>>1; lson[root]=build(l,mid); rson[root]=build(mid+1,r); } return root; } int update(int root,int pos,int val) { int newroot=tot++,tmp=newroot; c[newroot]=c[root]+val; int l=1,r=n; while(l<r) { int mid=(l+r)>>1; if(pos<=mid) { lson[newroot]=tot++; rson[newroot]=rson[root]; newroot=lson[newroot]; root=lson[root]; r=mid; }else { rson[newroot]=tot++; lson[newroot]=lson[root]; newroot=rson[newroot]; root=rson[root]; l=mid+1; } c[newroot]=c[root]+val; } return tmp; } int query(int root,int pos) { int ret=0; int l=1,r=n; while(pos<r) { int mid=(l+r)>>1; if(pos<=mid) { r=mid; root=lson[root]; }else { ret+=c[lson[root]]; root=rson[root]; l=mid+1; } } return ret+c[root]; } int main() { while(scanf("%d",&n)==1) { tot=0; for(int i=1;i<=n;i++) scanf("%d",&a[i]); T[n+1]=build(1,n); map<int,int> mp; for(int i=n;i>=1;i--) { if(mp.find(a[i])==mp.end()) { T[i]=update(T[i+1],i,1); }else { int tmp=update(T[i+1],mp[a[i]],-1); T[i]=update(tmp,i,1); } mp[a[i]]=i; } scanf("%d",&q); while(q--) { int l,r; scanf("%d%d",&l,&r); printf("%d\n",query(T[l],r)); } } return 0; }
相关文章推荐
- SPOJ3267 D-Query 树状数组离线操作 或 主席树 查询某一区间内有多少不同的数
- SPOJ 3267. D-query (主席树,查询区间有多少个不相同的数)
- D-query SPOJ - DQUERY 查询区间有多少个不同的数(SPOJ DQUERY)
- SPOJ - DQUERY 主席树求区间有多少个不同的数(模板)
- SPOJ 3267. D-query (主席树,查询区间有多少个不相同的数)
- CDOJ 1104 求两个数列的子列的交集 查询区间小于A的数有多少个 主席树
- HDU 5919 Sequence II (主席树+求区间不同数个数)
- HDU 5919 Sequence II(主席树+区间不同数个数+区间第k小)
- 【HDU5654 BestCoder Round 77 (div1) D】【前驱位置思想 排序 树状数组】xiaoxin and his watermelon candy 区间内多少个不同连续单升三元
- 查询区间内不同数字的个数 lydsy1878
- hdu 5919 Sequence II (主席树,求区间不同数的个数)
- SPOJ TTM - To the moon (主席树,区间更新,区间查询)
- 经典问题:查询有多少段区间和等于k值
- SPOJ:D-query(非常规主席树求区间不同数的个数)
- HDU 4348 主席树(新的线段树区间查询方法)
- SPOJ TTM To The Moon 主席树的区间更新与查询
- SPOJ-DQUERY-主席树求区间不同数个数模板
- spoj 3267. D-query 主席树求区间不同数的个数
- SPOJ DQUERY(树状数组离线处理 or 主席树 区间不同数个数)
- spoj DQUERY - D-query(区间不同数的个数 主席树 or BIT)