•【例3-1】找树根和孩子
【问题描述】
给定一棵树,输出树的根root,孩子最多的结点max以及他的孩子
【输入格式】
第一行:n(结点数<=100),m(边数<=200)。
以下m行;每行两个结点x和y,
表示y是x的孩子(x,y<=1000)。
【输出格式】
第一行:树根:root。
第二行:孩子最多的结点max。
第三行:max的孩子。
简单方法
1 #include<iostream>
2 using namespace std;
3 int tree[101];
4 int maxn=0;
5 int maxnroot;
6 int main()
7 {
8 int n,m;
9 int root=-1;
10 cin>>n>>m;
11 for(int i=1;i<=m;i++)
12 {
13 int x,y;
14 cin>>x>>y;
15 tree[y]=x;
16 }
17 for(int i=1;i<=n;i++)
18 {
19 if(tree[i]==0)
20 {
21 root=i;
22 }
23 }
24 for(int i=1;i<=n;i++)
25 {
26 int sum=0;
27 for(int j=1;j<=n;j++)
28 {
29 if(tree[j]==i)
30 {
31 sum++;
32 }
33 }
34 if(sum>maxn)
35 {
36 maxn=sum;
37 maxnroot=i;
38 }
39 }
40 cout<<root<<endl;
41 cout<<maxnroot<<endl;
42 for(int i=1;i<=n;i++)
43 {
44 if(tree[i]==maxnroot)
45 {
46 cout<<i<<" ";
47 }
48 }
49 return 0;
50 }
父亲孩子表示法
1 #include<iostream>
2 using namespace std;
3 int tree[101];
4 int maxn=0;
5 int maxnroot;
6 int main()
7 {
8 int n,m;
9 int root=-1;
10 cin>>n>>m;
11 for(int i=1;i<=m;i++)
12 {
13 int x,y;
14 cin>>x>>y;
15 tree[y]=x;
16 }
17 for(int i=1;i<=n;i++)
18 {
19 if(tree[i]==0)
20 {
21 root=i;
22 }
23 }
24 for(int i=1;i<=n;i++)
25 {
26 int sum=0;
27 for(int j=1;j<=n;j++)
28 {
29 if(tree[j]==i)
30 {
31 sum++;
32 }
33 }
34 if(sum>maxn)
35 {
36 maxn=sum;
37 maxnroot=i;
38 }
39 }
40 cout<<root<<endl;
41 cout<<maxnroot<<endl;
42 for(int i=1;i<=n;i++)
43 {
44 if(tree[i]==maxnroot)
45 {
46 cout<<i<<" ";
47 }
48 }
49 return 0;
50 }
父亲孩子表示法
1 #include<iostream>
2 using namespace std;
3 struct node
4 {
5 int parent;
6 int child[101];
7 int hzsl;
8 int date;
9 }tree[101];
10 int main()
11 {
12 int n,m;
13 cin>>n>>m;
14 for(int i=1;i<=m;i++)
15 {
16 int x,y;
17 cin>>x>>y;
18 tree[x].child[tree[x].hzsl]=y;
19 tree[x].hzsl++;
20 tree[y].parent=x;
21 }
22 for(int i=1;i<=n;i++)
23 {
24 if(tree[i].parent==0)
25 {
26 cout<<i<<endl;
27 }
28 }
29 int maxn=0;
30 int maxnroot=0;
31 for(int i=1;i<=n;i++)
32 {
33 if(tree[i].hzsl>maxn)
34 {
35 maxn=tree[i].hzsl;
36 maxnroot=i;
37 }
38 }
39 cout<<maxnroot;
40 for(int i=0;i<tree[maxnroot].hzsl;i++)
41 {
42 cout<<tree[maxnroot].child[i]<<" ";
43 }
44 return 0;
45 }