Test instructions
N points form a tree. gives the root node p and the tree structure information.
Outputs the f[i of each point]. F[i]: The number of numbers in all sub-nodes with a number smaller than I in the root of I.
0<n<=10^5
Ideas:
Method One: Direct DFS, enter the node x to record the number of smaller than X. When you come out X, record the number of smaller numbers than X. Subtraction is f[x]. Combines a tree-like array.
Method Two: Write down the DFS sequence. Builds a segment tree for the DFS sequence. Then the nodes are inserted from small to large. Statistics by line segment tree.
Code: (Method One)
int Constn=1e5+5;intN,p;vector<int>G[n];intC[n];intAns[n];stack<int>S;BOOLVis[n];voidADD (intx) { for(inti=x;i<=n;i+=lowbit (i)) {C[i]++; }}intQueryintx) { intret=0; for(intI=x;i>0; i-=lowbit (i)) {ret+=C[i]; } returnret;}voidDfsintu) { while(!S.empty ()) {S.pop (); } mem (Vis,false); S.push (U); Vis[u]=true; while(!S.empty ()) { intnow=S.top (); intL=g[now].size (); BOOLflag=false; Rep (I,0, L-1){ if(vis[g[now][i]]==false) {Vis[g[now][i]]=true; Flag=true; intt=G[now][i]; Ans[t]=query (t1); S.push (G[now][i]); Break; } } if(!flag) {Ans[now]=query (now-1)-Ans[now]; ADD (now); S.pop (); } }}intMain () { while(SCANF ("%d%d", &n,&p)!=eof,n| |p) {Rep (i,1nn) G[i].clear (); Mem (C,0); Mem (ans,0); Rep (I,1, N-1){ intb; scanf ("%d%d",&a,&b); G[a].push_back (b); G[b].push_back (a); } DFS (P); Rep (I,1, N-1) printf ("#df", Ans[i]); cout<<ans[n]<<Endl; } return 0;}
HDU 3887 counting offspring (Dfs sequence "non-recursive" + Tree-like array)