【題目來源】
https://www.acwing.com/problem/content/1256/
【題目描述】
給定一棵樹,輸出樹的根root,孩子最多的結點max以及他的孩子。
【輸入格式】
第一行:n,m,表示樹的節點數和邊數。
以下m行:每行兩個結點x和y,表示y是x的孩子。
【輸出格式】
第一行:樹根:root;
第二行:孩子最多的結點max;
第三行:max的孩子(按編號由小到大輸出)。
【數據范圍】
1≤n≤100,
m=n?1,
1≤x,y≤1000,
數據保證孩子最多的結點唯一。
【輸入樣例1】
8 7
4 1
4 2
1 3
1 5
2 6
2 7
2 8
【輸出樣例1】
4
2?
6 7 8
【輸入樣例2】
10 9
661 43
43 270
43 155
155 691
661 201
661 768
661 889
43 302
201 98
【輸出樣例2】
661
661
43 201 768 889
【算法分析】
本題是樹的遍歷問題,不是二叉樹。
【算法代碼】
#include <bits/stdc++.h>
using namespace std;const int N=1010;
bool st[N];
vector<int> g[N];
int fa,son;
int n,m;int main() {cin>>n>>m;for(int i=0; i<m; i++) {cin>>fa>>son;st[son]=true; //has fatherg[fa].push_back(son);}for(int i=1; i<=1000; i++) { //find rootif(g[i].size()) { //if node i has sonif(!st[i]) { //and node i hasn't fathercout<<i<<endl;break;}}}int p=1;for(int i=2; i<=1000; i++) //Find the node with the most sonsif(g[i].size()>g[p].size()) p=i;cout<<p<<endl;sort(g[p].begin(),g[p].end()); //Sort the son from small to bigfor(auto x:g[p]) cout<<x<<" ";cout<<endl;return 0;
}/*
in:
8 7
4 1
4 2
1 3
1 5
2 6
2 7
2 8out:
4
2
6 7 8
*/
【參考文獻】
https://www.acwing.com/solution/content/66005/
https://www.acwing.com/solution/content/36119/
?