Find the root and child, and find the root child
• [Example 3-1] find the root of the tree and the child. [Problem description] specify a tree and output the root of the tree, the maximum node max of the child, and the first line of his/her child input format: n (number of knots <= 100) and m (number of edges <= 200 ). The following m rows. Each line has two nodes x and y, indicating that y is the child of x (x, y <= 1000 ). Output Format: the first line: root. Row 2: The largest node max for children. Row 3: The child of max. Simple Method
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 }
Father-Child notation
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}
Father-Child notation
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 }