本文主要是介绍【PAT】【Advanced Level】1004. Counting Leaves (30),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1004. Counting Leaves (30)
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 Input2 1 01 1 02Sample 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;
}
这篇关于【PAT】【Advanced Level】1004. Counting Leaves (30)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!