【PAT】【Advanced Level】1004. Counting Leaves (30)

xiaoxiao2021-02-28  88

1004. Counting Leaves (30)

时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue 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

原题链接:

https://www.patest.cn/contests/pat-a-practise/1004

思路:

map匹配节点在数组中的下标,类似于索引功能

先读入数据,添加父子关系

然后DFS,确定层数并统计各层目标点个数

最后输出

CODE:

#include<iostream> #include<cstring> #include<string> #include<map> #include<vector> #define N 101 using namespace std; typedef struct no { string id; string son[N]; int ns; }; map<string,int> pos; int m,n; no p[N]; int mf=0; int outp[N]; void dfs(string r,int fl) { mf=max(mf,fl); if (p[pos[r]].ns==0) { outp[fl]++; return ; } for (int i=0;i<p[pos[r]].ns;i++) { dfs(p[pos[r]].son[i],fl+1); } return; } int main() { cin>>n>>m; int num=1; for (int i=0;i<m;i++) { string a; cin>>a; int t; if (pos[a]==0) { p[num].id=a; p[num].ns=0; pos[a]=num; t=num; num++; } else { t=pos[a]; } int k; cin>>k; for (int j=0;j<k;j++) { string ss; cin>>ss; p[t].son[p[t].ns]=ss; p[t].ns++; if (pos[ss]==0) { p[num].id=ss; p[num].ns=0; pos[ss]=num; num++; } } } memset(outp,0,sizeof(outp)); dfs("01",0); for (int i=0;i<mf;i++) cout<<outp[i]<<" "; cout<<outp[mf]; return 0; }

转载请注明原文地址: https://www.6miu.com/read-79191.html

最新回复(0)