Seek leaf node

Gives a tree of n nodes, the node numbered 1-n (root node number 1), seeking the number of leaf nodes of this tree.

E.g:

1─2─4─5
└─3

3 and 5 which are leaf nodes, output 2.

Input First line: a number n (1 <n <= 1000), indicates the number of nodes of the tree. Back row n-1: the number of each line 2 xy, x indicates the node is a parent of node y (1 <= x, y <= n). Output Output number 1, this tree represents the number of leaf nodes. Sample Input

5
1 2
1 3
2 4
4 5

Sample Output

2 

a variety Solution
a: assumed full leaf nodes, the node is not a leaf array record, to subtract
#include<bits/stdc++.h>
using namespace std;
const int maxn=1010;
int a[maxn];
int main()
{
    int n,x,y,sum;
    memset(a,0,sizeof(a));
    cin>>n;
    sum=0;
    for(int i=1;i<n;i++)
    {
        cin>>x>>y;
        if(a[x]==0)
        {
            a[x]++;
            sum++;
        }
    }
    cout<<n-sum<<endl;
    return 0;
 } 

II: The memory map, the degree of behavior, as the degree of

#include<bits/stdc++.h>
using namespace std;
const int maxn=1010;
bool a[maxn][maxn];
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<n;i++)
    {
        int x,y;
        cin>>x>>y;
        a[x][y]=1;
    }
    int cnt=0;
    for(int i=1;i<n;i++)
    {
        bool flag=0;
        for(int j=1;j<n;j++)
            if(a[i][j]) flag=1;
        if(flag==0) cnt++;
    }
    cout<<cnt<<endl;
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/ylrwj/p/12298561.html