时间限制:1秒 内存限制:128M
题目描述
给定一棵树,输出树的根root,孩子最多的结点max以及他的孩子。
输入描述
第一行:n(结点个数≤100),m(边数≤200)。 以下m行:每行两个结点x和y,表示y是x的孩子(x,y≤100)。
输出描述
第一行:树根:root; 第二行:孩子最多的结点max(多个只输出编号最小的结点); 第三行:max的孩子(按编号由小到输出)。
样例
输入
8 7 4 1 4 2 1 3 1 5 2 6 2 7 2 8
输出
4 2 6 7 8
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
int n,m;
int x,y;
const int N=1e6+10;
int tree[N],maxx,root,i,maxroot;
int main() {
cin>>n>>m;
int sum=0,j,maxx=0;
for(int i=1; i<=m; i++) {
cin>>x>>y;
tree[y]=x;
}
for(int i=1; i<=n; i++) {
if(tree[i]==0){
root=i;
break;
}
}
for(int i=1; i<=n; i++) {
sum=0;for(int j=1;j<=n;j++){
if(tree[j]==i){
sum++;
}
if(sum>maxx){
maxx=sum;
maxroot=i;
}
}
}
cout<<root<<endl<<maxroot<<endl;
for(int i=1;i<=n;i++){
if(tree[i]==maxroot){
cout<<i<<" ";
}
}
return 0;
}