PAT (Advanced Level) 1004. Counting Leaves (30) BFS

题目链接

Counting Leaves

Time limit:1 seconds Memory limit:256 megabytes


Problem Description

A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

Input

Each input file contains one test case. Each case starts with a line containing 0 < N < 100, the number of nodes in a tree, and M (< N), the number of non-leaf nodes. Then M lines follow, each in the format:

ID K ID[1] ID[2] … ID[K]

where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID’s of its children. For the sake of simplicity, let us fix the root ID to be 01.

Output

For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.

The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output “0 1” in a line.

Input

2 1
01 1 02

Output

0 1


题意:

给一颗数,求每层的叶子节点数

解题思路:

树的层次遍历,BFS时记录一下深度就可以啦

Code:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;

const int maxn=105,maxm=maxn*maxn;
struct Edge
{
    int to,next;
};

struct Node
{
    int id;
    int depth;
};

Edge e[maxm];
int head[maxn];
bool vis[maxn];
int N,M;
int edge;
int ans[maxn],max_dep=0;
queue<Node> Q;

void init()
{
    edge=0;
    memset(head,-1,sizeof(head));
}

void addEdge(int u,int v)
{
    e[edge].to=v,e[edge].next=head[u],head[u]=edge++;
}

void BFS()
{
    memset(vis,false,sizeof(vis));
    while(!Q.empty())
        Q.pop();
    vis[1]=true;
    Q.push(Node{1,0});
    while(!Q.empty())
    {
        Node u=Q.front();
        Q.pop();
        int id=u.id;
        //cout<<id<<endl;
        int depth=u.depth;
        max_dep=max(max_dep,depth);
        if(head[id]==-1)
            ans[depth]++;
        vis[id]=true;
        for(int i=head[id];i!=-1;i=e[i].next)
        {
            int v=e[i].to;
            if(!vis[v])
            {
                Q.push(Node{v,depth+1});
            }
        }
    }
}

int main()
{
    init();
    int n,m;
    cin>>n>>m;
    for(int i=0;i<m;i++)
    {
        int u,k;
        cin>>u>>k;
        for(int j=0;j<k;j++)
        {
            int v;
            cin>>v;
            addEdge(u,v);
        }
    }
    BFS();
    for(int i=0;i<=max_dep;i++)
    {
        cout<<ans[i];
        if(i==max_dep)
            cout<<endl;
        else
            cout<<" ";
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xp731574722/article/details/79498323