这里是按层求最大节点个数及所在的层数,所以要每条路走一遍记录一下。
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
using namespace std;
const int maxn = 110;
vector<int>node[maxn];
int hashtable[maxn];
int maxLevel = -1;
void dfs(int index, int level)
{
hashtable[level]++;
if (level > maxLevel)
maxLevel = level;
if (node[index].size() == 0)
return;
for (int i = 0; i < node[index].size(); i++)
{
dfs(node[index][i], level + 1);
}
}
int main()
{
int n, m, parent, k, child;
cin >> n >> m;
for (int i = 0; i < m; i++)
{
cin >> parent >> k;
for (int j = 0; j < k; j++)
{
cin >> child;
node[parent].push_back(child);
}
}
dfs(1, 1);
int maxlevel = 0, maxcount = 0;
for (int i = 1; i <= maxLevel; i++)
{
if (hashtable[i] > maxcount)
{
maxcount = hashtable[i];
maxlevel = i;
}
}
cout << maxcount << " " << maxlevel << endl;
}
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
using namespace std;
const int maxn = 110;
vector<int>node[maxn];
int hashtable[maxn];
int level[maxn];
int maxLevel = -1;
void bfs(int index)
{
queue<int>q;
q.push(index);
level[index] = 1;
while (!q.empty())
{
int temp = q.front();
q.pop();
hashtable[level[temp]]++;
for (int i = 0; i < node[temp].size(); i++)
{
q.push(node[temp][i]);
level[node[temp][i]] = level[temp] + 1;
}
}
}
int main()
{
int n, m, parent, k, child;
cin >> n >> m;
for (int i = 0; i < m; i++)
{
cin >> parent >> k;
for (int j = 0; j < k; j++)
{
cin >> child;
node[parent].push_back(child);
}
}
bfs(1);
int maxlevel = 0, maxcount = 0;
for (int i = 1; i <= maxn; i++)
{
if (hashtable[i] > maxcount)
{
maxcount = hashtable[i];
maxlevel = i;
}
}
cout << maxcount << " " << maxlevel << endl;
}