原题:https://pintia.cn/problem-sets/994805342720868352/problems/994805372601090048
Find the leve which has the largest node number!
首先建立一般的树,然后BFS求所有结点的层数,最后找到最多的一层。
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include<stack>
#include<queue>
#include<sstream>
using namespace std;
/*
A1094 The Largest Generation (25 分)
树
*/
const int MaxN = 110;
struct node {
vector <int> Child; //孩子的ID
int level=-1; //代数
};
node P[MaxN]; //这里从1开始编号,对应ID
//令P[ID].level=level, 并给其孩子generation赋值
void BFS(int ID, int level) {
P[ID].level = level;
for (int i = 0; i < P[ID].Child.size(); i++) {
BFS(P[ID].Child[i], level + 1);
}
return;
}
int main() {
//freopen("input.txt", "r", stdin);
int N; //N (<100) which is the total number of family members in the tree
int M; //M (<N) which is the number of family members who have children
cin >> N >> M;
for (int i = 0; i < M; i++) {
int Parent,num;
cin >> Parent>>num;
for (int j = 0; j < num; j++) {
int temp;
cin >> temp;
P[Parent].Child.push_back(temp);
}
}
BFS(01, 1);
int ge[MaxN] = { 0 }; //每一代的人数, 从1编号到N
for (int i = 1; i <= N; i++) {
ge[P[i].level]++;
}
//找最大的一代
int MAX=0, G_MAX=-1;
for (int i = 1; i <= N; i++) {
if (ge[i] > MAX) {
MAX = ge[i];
G_MAX = i;
}
}
cout << MAX << " " << G_MAX << endl;
return 0;
}