PAT 甲級 1004 Counting Leaves (30 分)
阿新 • • 發佈:2021-02-12
技術標籤:PAT-Advancedc++
Note
- 樹的遍歷 – BFS
- 簡單題
Code
#include<bits/stdc++.h>
using namespace std;
int max_level=-1,level[100];
int counts[100]={0};
vector<int> tree[100];
void bfs(int root){
queue<int> q;
q.push(root);
level[root]=1;
while(!q.empty()){
int data=q.front();
q.pop();
if (level[data]>max_level) max_level=level[data];
if(tree[data].empty()) counts[level[data]]++;
for(int i=0;i<tree[data].size();i++){
q.push(tree[data][i]);
level[tree[data][i]]=level[data]+1;
}
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("data.txr","r",stdin);
#endif
int n,m,k,id,ch;
scanf("%d %d",&n,&m);
for(int i=0;i<m;i++){
scanf("%d %d",&id,&k);
for(int j=0;j<k;j++){
scanf("%d",&ch);
tree[id].push_back(ch);
}
}
bfs(1);
for(int i=1;i<=max_level;i++){
if(i!=1) printf(" " );
printf("%d",counts[i]);
}
return 0;
}