Find roots and children

【Problem Description】   

Given a tree, the root of the tree root output, most child node and his child max

[Input Format]   

The first line: n (number of nodes <= 100), m (the number of edges <= 200).   

The following lines m; each row of the two nodes x and y, x and y is represented by a child (x, y <= 1000).

[Output format]   

First line: root: root.   

The second line: most children nodes max.   

Third row: max children.

[Sample input]   

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

[Sample Output]   

4   2   6 7 8


[A solution]

 

Solution [two]

 1 #include<iostream>
 2 using namespace std;
 3 int n,m,tree[101]={0};
 4 int main()
 5 {
 6   int i,x,y,root,maxroot,sum=0,j,Max=0;
 7   cin>>n>>m;
 8   for(i=1;i<=m;i++)
 9   {
10     cin>>x>>y;
11     tree[y]=x;
12    }
13   for(i=1; I <= n-; I ++)                      // find the root 
14       IF (Tree [I] == 0 )
 15        {
 16          the root = I; BREAK ;
 . 17        }
 18 is    for (I = . 1 ; I <= n-; I ++) // Get the most child node 
. 19     {
 20 is       SUM = 0 ;  
 21 is       for (J = . 1 ; J <= n-; J ++ )
 22 is          IF (Tree [J] == I) SUM ++ ;
 23 is       IF (SUM> Max)
 24        {
 25          Max=sum;maxroot=i;
26       }
27    }    
28    cout<<root<<endl<<maxroot<<endl;  
29    for(i=1;i<=n;i++)
30      if(tree[i]==maxroot) cout<<i<<" ";
31    return 0; 
32 }

 

Guess you like

Origin www.cnblogs.com/ljy-endl/p/11260460.html