• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
山不在高,有金则名!
博客园    首页    新随笔    联系   管理    订阅  订阅

1336:【例3-1】找树根和孩子

【题目描述】

给定一棵树,输出树的根rootroot,孩子最多的结点maxmax以及他的孩子。

【输入】

第一行:nn(结点个数≤100≤100),mm(边数≤200≤200)。

以下mm行:每行两个结点xx和yy,表示yy是xx的孩子(x,y≤1000x,y≤1000)。

【输出】

第一行:树根:rootroot;

第二行:孩子最多的结点maxmax;

第三行:maxmax的孩子(按编号由小到输出)。

【输入样例】

8 7
4 1
4 2
1 3
1 5
2 6
2 7
2 8

【输出样例】

4
2 
6 7 8
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int n, m;
    cin >> n >> m;
    vector<int> dad(n + 1);
    vector <set<int>> son(n + 1);
    int x, y; // y是x的孩子
    for (int i = 0; i < m; i++) {
        cin >> x >> y;
        dad[y] = x;
        son[x].insert(y);
    }
    int root = x;
    while (dad[root] != 0) {
        root = dad[root];
    }
    int max = 1;
    for (int i = 2; i < son.size(); i++) {
        if (son[max].size() < son[i].size()) {
            max = i;
        }
    }
    cout << root << endl;
    cout << max << endl;
    for (set<int>::iterator it = son[max].begin();
         it != son[max].end(); ++it) {
        cout << *it << " ";
    }
    return 0;
}

 

posted @ 2021-06-27 20:06  杭州山不高  阅读(623)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3