PAT 甲級 1004. Counting Leaves 使用深度遍歷(DFS)

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.

Sample Input
2 1
01 1 02
Sample Output
0 1

題目大概意思,就是統計每一代人中沒有孩子的個數,轉化爲一顆樹,就是統計每一層中葉子結點的個數,使用map可以很好解決對於每個人的孩子的存儲,由於id是2位數,用string類型,孩子用vector<string>,就是父母的類型是map<string,vector<string>>。

用dfs,由於要走完全過程,以及要保留當前是哪一層,所以不用對是否爲終點進行判斷 ,dfs的模板dfs(start,end)改爲dfs(string start,int c)c用來記錄層數


#include <iostream>
#include "cstring"
#include <stdio.h>
#include "iomanip"
#include "vector"
#include "cmath"
#include "stack"
#include "algorithm"
#include <math.h>
#include "map"
#include "queue"
using namespace std;
map <string,vector<string> >a;//有孩子的父母節點
map <string,int>visit;//是否有被訪問過
int cc=0;//記錄總共有多少代,也就是數的層數
int kid[100]={0};//記錄第k層葉子結點的個數
void  dfs(string start,int c)//深度遍歷
{
    if(visit[start]==1)
        return  ;
    visit[start]=1;
    if(a[start].size()==0)
    kid[c]++;
    cc=max(cc,c++);
    for(int i=0;i< a[start].size();i++ )
    {
        if(visit[a[start][i]]==1)
        return  ;
        dfs(a[start][i],c);
    }
}
int main()
{
     
    int n,m,i;
    cin>>n>>m;
    while(m--)
    {
        string t,tt;
        cin>>t>>i;
        visit[t]=0;
        while(i--)
        {
            cin>>tt;
            a[t].push_back(tt);
            visit[tt]=0;
        }
    }
     dfs("01",0);

    for(i=0;i<=cc;i++)
    {
        cout<<kid[i];
        if(i!=cc)
            cout<<" ";
    }
        cout<<endl;

 return  0;


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章