Chairman Tree
1#include <cstdio>2#include <algorithm>3#include <map>4 #defineN 20000105 using namespacestd;6map<int,int>Ma;7 intn,m,i,a,b,c,e[n],last,d[n],id[n],deep[n],j;8 intDp,pre[n],p[n],tt[n],l[n],r[n],ls[n],rs[n],s[n],tot,root[n];9 intjump[100100][ +];Ten voidLinkintXinty) One { Adp++;p re[dp]=p[x];p [x]=dp;tt[dp]=y; - } - voidBuildint&x,intAintb) the { -tot++;x=tot; -l[x]=a;r[x]=b; - if(b-a>1) + { - intM= (a+b) >>1; + build (ls[x],a,m); A build (rs[x],m,b); at } - } - voidInsertint&x,intYintAintb) - { -tot++;x=tot; -l[x]=l[y];r[x]=R[y]; inls[x]=ls[y];rs[x]=rs[y];s[x]=S[y]; - if((A<=l[x]) && (r[x]<=b)) to { +s[x]++; - return; the } * intM= (L[x]+r[x]) >>1; $ if(a<m) insert (LS[X],LS[Y],A,B);Panax Notoginseng if(m<b) Insert (RS[X],RS[Y],A,B); -s[x]=s[ls[x]]+S[rs[x]]; the } + voidDfsintXintFA) A { the intI=P[x]; +Insert (root[x],root[fa],e[x]-1, e[x]); -jump[x][0]=FA; $deep[x]=deep[fa]+1; $ while(i) - { - if(tt[i]!=FA) Dfs (tt[i],x); theI=Pre[i]; - }Wuyi } the intQueryintXintYintZintWintc) - { Wu if(r[x]-l[x]==1) - { About returnR[x]; $ } - inttmp=s[ls[x]]+s[ls[y]]-2*S[ls[z]]; - if((l[ls[x]]<w) && (W<=r[ls[x])) tmp++; - if(tmp>=c) A returnquery (ls[x],ls[y],ls[z],w,c); + Else the returnQuery (rs[x],rs[y],rs[z],w,c-tmp); - } $ intLcaintAintb) the { the inti; the if(Deep[a]<deep[b]) a^=b^=a^=b; the for(i= -; i>=0; i--) - if(Deep[jump[a][i]]>=deep[b]) a=Jump[a][i]; in if(a==b)returnA; the the for(i= -; i>=0; i--) About if(jump[a][i]!=Jump[b][i]) the { theA=Jump[a][i]; theb=Jump[b][i]; + } - returnjump[a][0]; the }Bayi intMain () the { thescanf"%d%d",&n,&m); - for(i=1; i<=n;i++) - { thescanf"%d",&e[i]); thed[i]=E[i]; the } theSort (d+1, d+1+N);intCnt=0;d [0]=-0x37373737; - for(i=1; i<=n;i++) the { the if(d[i]!=d[i-1]) cnt++; thema[d[i]]=CNT;94id[cnt]=D[i]; the } the for(i=1; i<=n;i++) e[i]=Ma[e[i]]; the for(i=1; i<n;i++)98 { Aboutscanf"%d%d",&a,&b); - Link (A, b);101 link (b,a);102 }103Build (root[0],0, CNT);104Dfs1,0); the 106 for(i=1; i<= -; i++)107 for(j=1; j<=n;j++)108jump[j][i]=jump[jump[j][i-1]][i-1];109 the 111 intans=0; the for(i=1; i<=m;i++)113 { thescanf"%d%d%d",&a,&b,&c); thea^=ans; the intLca=LCA (A, b);117 //printf ("%d%d%d\n", S[ROOT[A]],S[ROOT[B]],LCA);118ans=id[query (root[a],root[b],root[lca],e[lca],c)];119printf"%d", ans); - if(i!=m) printf ("\ n");121 }122 123}
bzoj2588 Spoj 10628. Count on a tree