还是层序遍历,继续BFS,很容易解决。
附本人AC代码:
#include<iostream>
#include<vector>
#include<queue>
#include<map>
using namespace std;
vector<vector<int>>V;
int leavel[110];
map<int, int>Ma;
int main() {
int N, M, num, id, val, maxleavel=0;
scanf("%d%d", &N, &M);
V.resize(N+1);
for (int i = 0; i < M; i++) {
scanf("%d %d", &id,&num);
for (int j = 0; j < num; j++) {
scanf("%d", &val);
V[id].push_back(val);
}
}
queue<int>Q;
Q.push(1);
while (Q.size() != 0) {
int t = Q.front();
Q.pop();
if (V[t].size() == 0)Ma[leavel[t]]++;
for (int i = 0; i < V[t].size(); i++) {
leavel[V[t][i]] = leavel[t] + 1;
if (leavel[V[t][i]] > maxleavel)maxleavel = leavel[t] + 1;
Q.push(V[t][i]);
}
}
for (int it = 0; it <= maxleavel;it++) {
if (it == 0)printf("%d", Ma[it]);
else printf(" %d", Ma[it]);
}
return 0;
}