题目链接:
传送门
思路:直接dfs或者bfs记录每层的节点数即可
代码:
dfs:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 105;
vector <int> g[maxn];
int h[maxn];
int mm;
void dfs(int u , int d) {
h[d]++;
mm = max(d , mm);
for(int i = 0 ; i < g[u].size() ; i++) {
int v = g[u][i];
dfs(v , d + 1);
}
}
int main() {
int n , m;
ios::sync_with_stdio(0);
cin >> n >> m;
for(int i = 0 ; i < m ; i++) {
int id , k;
cin >> id >> k;
while(k--) {
int t;
cin >> t;
g[id].push_back(t);
}
}
mm = 0;
dfs(1 , 1);
int p = 1 , ans = 0;
for(int i = 1 ; i <= mm ; i++) {
if(ans < h[i]) {
p = i;
ans = h[i];
}
}
cout << ans << " " << p << "\n";
return 0;
}
bfs:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 105;
vector <int> g[maxn];
int h[maxn] , level[maxn];
int main() {
int n , m;
ios::sync_with_stdio(0);
cin >> n >> m;
for(int i = 0 ; i < m ; i++) {
int id , k;
cin >> id >> k;
while(k--) {
int t;
cin >> t;
g[id].push_back(t);
}
}
mm = 0;
queue <int> q;
level[1] = 1;
q.push(1);
while(!q.empty()) {
int u = q.front(); q.pop();
h[level[u]]++;
for(int i = 0 ; i < g[u].size() ; i++) {
int v = g[u][i];
level[v] = level[u] + 1;
q.push(v);
}
}
int p = 1 , ans = 0;
for(int i = 1 ; i <= n && h[i] ; i++) {
if(ans < h[i]) {
p = i;
ans = h[i];
}
}
cout << ans << " " << p << "\n";
return 0;
}