HDU 3887 counting offspring (Dfs sequence "non-recursive" + Tree-like array)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.