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;
}
發佈了174 篇原創文章 · 獲贊 322 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章