1004 Counting Leaves - dfs、樹的處理
阿新 • • 發佈:2018-11-09
思路:前向星+dfs
程式碼如下:
#include<iostream> #include<cstdio> #include<algorithm> #include<string> #include<cstring> #include<queue> #include<cmath> #include<set> #include<sstream> #define ll long long using namespace std; const int N=105,INF=0x3f3f3f3f; int flag[N],A[N],head[N],cnt=0,shen=0; struct proc{int to,next;}; proc edge[N]; void addEdge(int from,int to){ edge[cnt].to=to; edge[cnt].next=head[from]; head[from]=cnt++; } void dfs(int now,int dep){ shen=max(shen,dep); int res; if(flag[now])res=0; else res=1; A[dep]+=res; for(int i=head[now];i!=-1;i=edge[i].next){ int dot=edge[i].to; dfs(dot,dep+1); } } int main(){ int n,m,u,k,a,b; scanf("%d%d",&n,&m); memset(head,-1,sizeof(head)); memset(flag,0,sizeof(flag)); while(m--){ scanf("%1d%1d",&a,&b); u=a*10+b; scanf("%d",&k); if(k)flag[u]=k; while(k--){ scanf("%1d%1d",&a,&b); int tmp=a*10+b; addEdge(u,tmp); } } dfs(1,1); printf("%d",A[1]); for(int i=2;i<=shen;i++)printf(" %d",A[i]); printf("\n"); }