PAT甲级 1004
来源:互联网 发布:重庆大学生就业知乎 编辑:程序博客网 时间:2024/05/16 17:21
Counting Leaves
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
用2个vector分别记录每个节点的孩子结点ID和每一层的结点ID。然后使用isLeaf数组判断某一节点是否有孩子。
#include<iostream>#include<stdio.h>#include<limits.h>#include<algorithm>#include<vector>using namespace std;const int maxn=100+1;vector<int> v[maxn],level[maxn];bool isLeaf[maxn];int maxHeight=0;void dfs(int cur,int height){ for(auto it=v[cur].begin();it!=v[cur].end();it++){ level[height].push_back(*it); dfs(*it,height+1); } maxHeight=max(maxHeight,height);}int main(){ freopen("./in","r",stdin); int n,m; scanf("%d %d",&n,&m); fill(isLeaf,isLeaf+n+1,true); int i,j; int id,k,tid; for(i=0;i<m;i++){ scanf("%d %d",&id,&k); if(k!=0){ isLeaf[id]=false; } for(j=0;j<k;j++){ scanf("%d",&tid); v[id].push_back(tid); } } level[1].push_back(0); dfs(1,2); if(isLeaf[1]){ printf("1"); }else{ printf("0"); } int cnt; for(i=2;i<maxHeight;i++){ cnt=0; for(auto it=level[i].begin();it!=level[i].end();it++){ if(isLeaf[*it]){ cnt++; } } printf(" %d",cnt); }}
- PAT(甲级)1004
- PAT甲级-1004
- PAT-甲级-1004
- PAT甲级1004
- PAT甲级1004
- PAT甲级1004CountingLeaves
- PAT甲级1004
- 浙大PAT甲级-1004
- PAT甲级 1004
- 【Pat】甲级1004
- PAT甲级 1004 树
- PAT甲级1001-1004
- PAT甲级1004Counting Leaves
- PAT甲级 1004 27/30
- PAT 甲级
- PAT甲级 1004 Counting Leaves (30)
- PAT甲级 A1025.PAT RANKING
- PAT 甲级 1025 PAT Ranking
- 命名管道
- 蔡蒂民-2015年年中总结报告.docx
- 各类参数校验(身份证,手机号等)验证UTIL
- c++远征之多态篇——运行时类型识别(RTTI)
- JavaWeb:Request和Response总结
- PAT甲级 1004
- 蔡蒂民-2015年年终总结报告.docx
- java中Proxy(代理与动态代理)
- Android CoordinatorLayout和Behavior的源码分析(一)
- 授权软件使用微信更改机器码挺方便的,做共享软件的可以参考一下
- LPC2478 KEIL linking errors
- 蔡蒂民-2016年年中总结报告.docx
- java中从键盘输入的三种方法
- 把POI的NumbericCellValue特殊处理