树的简单问题

找树根和孩子

题目描述

给定一颗树,输出树的根root,孩子最多的结点max以及他的孩子。

输入

第一行:n(结点个数<=100)m(边树<=100)
以下m行:每行俩个结点x和y,表示y是x的孩子(x,y<=1000)

输出

第一行:树根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<cstring>
const int maxn =105;
using namespace std;
int tree[maxn];
int n,m;
int main()
{
 ios::sync_with_stdio(false);//小妹的习惯,大家自动忽略 
 cin.tie(0);cout.tie(0);
 cin>>n>>m;
 memset(tree,0,sizeof(tree));//初始化树 
 int x,y,root,maxroot,sum=0,max=-1;
 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>max)
    {
     max=sum;
     maxroot=i;
    }
   }
  }
  cout<<root<<endl;
  cout<<maxroot<<endl;
  for(int i=1;i<=n;i++)
  {
   if(tree[i]==maxroot) cout<<i<<" ";
  }
  return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值