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;


}


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