PAT1004 Counting Leaves
来源:互联网 发布:gta5ol女角色捏脸数据 编辑:程序博客网 时间:2024/05/23 13:27
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
思路:bfs,加两个变量leftNum和curNum,表示当前层和下一层。
#include<cstdio>#include<queue>#include<algorithm>#include<vector>#include<cstring>using namespace std;const int maxn=105;int n,m,level=0;vector<int>v[maxn],cnt;void solve(){ int leftNum=1,curNum=0,tot=0,root,len; queue<int>q; q.push(1); if(v[1].size()==0){ tot++; } cnt.push_back(tot); tot=0; while(!q.empty()){ root=q.front(); q.pop(); leftNum--; len=v[root].size(); curNum+=len; for(int i=0;i<len;i++){ if(v[v[root][i]].size()==0){ tot++; } q.push(v[root][i]); } if(leftNum==0){ //最后一层不处理 if(curNum){ leftNum=curNum; curNum=0; cnt.push_back(tot); tot=0; } } }}int main(){ //freopen("in.txt","r",stdin); int num,fa,child; scanf("%d%d",&n,&m); for(int i=0;i<m;i++){ scanf("%d%d",&fa,&num); for(int i=0;i<num;i++){ scanf("%d",&child); v[fa].push_back(child); } } solve(); printf("%d",cnt[0]); for(int i=1;i<cnt.size();i++){ printf(" %d",cnt[i]); } printf("\n"); return 0;}
- 【PAT1004】Counting Leaves
- PAT1004. Counting Leaves (30)
- pat1004 Counting Leaves
- [搜索]PAT1004 Counting Leaves
- PAT1004. Counting Leaves
- 【PAT1004】Counting Leaves
- pat1004 Counting Leaves
- PAT1004. Counting Leaves bfs
- PAT1004 Counting Leaves
- Counting Leaves
- Counting Leaves
- pat 1004 Counting Leaves
- pat 1004 counting Leaves
- 1004. Counting Leaves
- 1004. Counting Leaves (30)
- 1004. Counting Leaves
- PAT_1004: Counting Leaves
- PAT 1004 Counting Leaves
- ijkplayer编译(Ubuntu + Win双系统)
- Android平板上开发应用的一点心得——精确适配不同的dpi和屏幕尺寸
- Servlet学习(七)Application
- Spring 注解的方式进行事务管理
- log(二)——MDC实现之ThreadLocal
- PAT1004 Counting Leaves
- C语言系统资源控制(getrlimit && setrlimit)
- windowsViaC/C++之设备I/O之文件设备
- firebase基础(一)<推送服务调研>
- 在新linux中使用proc_create_data编写proc
- 兔子与樱花(map+最短路+记录路径)
- Swift_ScrollVoew&&PageControl
- JAVA序列化之RMI远程调用
- 串口重定向