8079 找树根和孩子--[中等-]

描述

给定一棵树,输出树的根 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;
}

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值