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