描述
给定一棵树,输出树的根 root,孩子最多的结点 max 以及他的孩子。
输入描述
第一行:n(结点个数≤100),m(边数≤200)。
以下 m 行:每行两个结点 x 和 y,表示 y 是 x 的孩子(x,y≤1000)。
输出描述
第一行:树根:root;
第二行:孩子最多的结点 max;
第三行:max 的孩子(按编号由小到输出)。
#include<bits/stdc++.h>
using namespace std;
struct node{
int childrencount;
int children[100];
bool hasparent;
}nodes[110];
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int n,m,x,y;
cin >>n >>m;
for(int i = 0;i < m;i++){
cin>>x>>y;
nodes[y].hasparent =true;
nodes[x].children[nodes[x].childrencount++] = y;
}
int root;
for(int i = 1;i <= n;i++){
if(!nodes[i].hasparent){
root = i;
break;
}
}
cout<<root<<endl;
int maxchildrencount = 0 , maxnode = -1;
for(int i = 1;i <= n;i++){
if(nodes[i].childrencount > maxchildrencount){
maxchildrencount = nodes[i].childrencount;
maxnode = i;
}
}
cout<<maxnode<<endl;
sort(nodes[maxnode].children,nodes[maxnode].children+nodes[maxnode].childrencount);
for(int i = 0;i < nodes[maxnode].children[i];i++){
cout<<nodes[maxnode].children[i]<<' ';
}
return 0;
}