"Algorithmic Learning Notes" 91. Simple forest count SJTU OJ 10,452 Brother's family

Source: Internet
Author: User

In fact, huge water ... But no scanf prinf at all. It's boring.

The first version of the code is a little bit inefficient, mainly considering the possibility that the family might have started out as a forest, not from a tree.

Actually, the data point is still a tree, and then it becomes a forest. So, as long as three arrays are available.

Alive is the record alive?

Sons record the number of child nodes for each person

Father records each person's parent can determine if x is the root node of a tree according to Alive[father[x]].

CNT Maintenance Family Number

Every time a dead person

Judging whether a dead person is a root node of a tree or just a leaf node.

#include <iostream>#include<vector>#include<algorithm>#include<cstdio>using namespacestd;Const intMAXN =200000+Ten;intN;intFATHER[MAXN] = {0};//record who the father of each person isBOOLALIVE[MAXN] = {false};//is the record alive ?intsons[maxn]={0};//record the number of sonsvoidinit () {cin>>N;}intCNT =1;//Number of familiesvoidbuild () { for(inti =0; i < N; ++i) {        Charop; Op=GetChar ();  while(op!='B'and op!='D') {op=GetChar (); }         while(OP! ='B'&& OP! ='D') scanf ("%c",&op); intx, y; Switch(OP) { Case 'B': scanf ("%d%d",&x,&y); if(!alive[x]) sons[x]=0; Father[y]= x;//Y's dad's X.ALIVE[X] = Alive[y] =true;//They 're both alive.sons[x]++;  Break;  Case 'D': scanf ("%d",&x); ALIVE[X]=false; if(!alive[father[x]])//It 's a root node, Dad's dead.cnt--; ElseSons[father[x]]--; CNT+=Sons[x]; //cout<<cnt<<endl;printf"%d\n", CNT);  Break; }    }}intMainintargcChar Const*argv[])    {init ();    Build (); return 0;}

"Algorithmic Learning Notes" 91. Simple forest count SJTU OJ 10,452 Brother's family

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.