还是层序遍历,老老实实用BFS,队列+while循环实现,写法简单,容易排错。
附本人AC代码:
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
vector < vector<int>>V;
int leavel[110], maxnum = 0, countnum[110], maxleavel;
int main() {
int N, M, id, num, val;
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);
}
}
leavel[1] = 1;
queue<int>Q;
Q.push(1);
while (Q.size()) {
int t = Q.front();
Q.pop();
countnum[leavel[t]]++;
if (countnum[leavel[t]] > maxnum) {
maxnum = countnum[leavel[t]];
maxleavel = leavel[t];
}
for (int i = 0; i < V[t].size(); i++) {
Q.push(V[t][i]);
leavel[V[t][i]] = leavel[t] + 1;
}
}
printf("%d %d", maxnum,maxleavel);
return 0;
}