PAT A1004 Counting Leaves (30分)(層序遍歷)
阿新 • • 發佈:2020-09-09
#include<cstdio> #include<queue> #include<vector> using namespace std; const int N = 110; int n; struct node{ int layer; bool isleaf = true; vector<int> child; }Node[N]; int leafinlayer[N]; int h=0; void layerorder(int root){ queue<int> q; q.push(root); Node[root].layer=0; while(q.empty()==false){ int front = q.front(); q.pop(); if(Node[front].isleaf==true){ if(h<Node[front].layer){ h = Node[front].layer; } leafinlayer[Node[front].layer]++; }else{ for(int i = 0;i<Node[front].child.size();i++){ int id = Node[front].child[i]; q.push(id); Node[id].layer = Node[front].layer+1; } } } return; } int main(){ int m; scanf("%d %d",&n,&m); for(int i = 0;i<m;i++){ int id,childnum; scanf("%d %d",&id,&childnum); Node[id].isleaf=false; for(int j = 0;j<childnum;j++){ int childid; scanf("%d",&childid); Node[id].child.push_back(childid); } } layerorder(1);//root預設為1 for(int i = 0;i<=h;i++){ printf("%d",leafinlayer[i]); if(i!=h){ printf(" "); } } }