#if 0#include<vector>usingnamespace std;#include<iostream>
vector<int>nodes[100];int depth[100];int maxdepth =0;voiddfs(int index,int deep){if(nodes[index].size()==0){// judge whether ID[index] has sons
depth[deep]++;
maxdepth = deep > maxdepth ? deep : maxdepth;//for later output at line 33return;}else{for(int i=0;i<nodes[index].size();i++)dfs(nodes[index][i], deep +1);}}intmain(){int N, M;
cin >> N >> M;for(int i =0; i < M; i++){int id, num;
cin >> id>>num;for(int j=0; j < num; j++){int son;
cin >> son;
nodes[id].push_back(son);//add son one by one}}if(N ==0)return0;dfs(1,0);
cout << depth[0];for(int i =1; i <= maxdepth; i++){
cout <<" "<< depth[i];}return0;}#endif
代码 BFS
#if 0#include<vector>usingnamespace std;#include<iostream>#include<queue>
vector<int>nodes[100];int depth[100],maxdepth =0;voidbfs(int index1){int deep =0;
queue<int>temp1, temp2;//"temp" includes all nodes in same depth
temp1.push(index1);while(!temp1.empty()){int index2 = temp1.front();
temp1.pop();if(nodes[index2].size()==0){//no son
depth[deep]++;
maxdepth = deep > maxdepth ? deep : maxdepth;}for(int i =0; i < nodes[index2].size(); i++){//push each son into temp2
temp2.push(nodes[index2][i]);}if(temp1.empty()){
temp1.swap(temp2);
deep++;}}}intmain(){int N, M;
cin >> N >> M;for(int i =0; i < M; i++){int id, num;
cin >> id >> num;for(int j =0; j < num; j++){int son;
cin >> son;
nodes[id].push_back(son);//add son one by one}}if(N ==0)return0;bfs(1);
cout << depth[0];for(int i =1; i <= maxdepth; i++){
cout <<" "<< depth[i];}return0;}#endif