信息學奧賽:1336:【例3-1】找樹根和孩子
1336:【例3-1】找樹根和孩子
時間限制: 1000 ms 內存限制: 65536 KB
提交數: 6501 通過數: 3340
【題目描述】
給定一棵樹,輸出樹的根root,孩子最多的結點max以及他的孩子。
【輸入】
第一行:n(結點個數≤100),m(邊數≤200)。
以下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<iostream>
#include<set>
using namespace std;
const int maxn = 202;
struct Node {
int father; // 父親只有一個
set<int>s; // 兒子千千萬
}node[maxn / 2];
int main() {
int n, m;
cin >> n >> m;
int father, child;
for (int i = 1; i <= n; i++)
node[i].father = -1;
for (int i = 1; i <= m; i++) {
cin >> father >> child;
node[child].father = father;
node[father].s.insert(child);
}
int max = 0, who;
for (int i = 1; i <= n; i++) {
if(node[i].father == -1)
cout << i << endl;
if (node[i].s.size() > max) {
max = node[i].s.size();
who = i;
}
}
cout << who << endl;
for (set<int>::iterator it = node[who].s.begin(); it != node[who].s.end(); it++)
cout << *it << ' ';
return 0;
}
// 數據結構樹基本不會,幾乎沒學過。看了趣味算法裏面的霍夫曼編碼用到了樹,這裏用結構體構造樹就是通過那裏想到的。