zoukankan      html  css  js  c++  java
  • A1004. Counting Leaves (30)

    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
     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <iostream>
     4 #include <string.h>
     5 #include <math.h>
     6 #include <algorithm>
     7 #include <string>
     8 #include <stack> 
     9 #include <queue>
    10 using namespace std;
    11 const int maxn=110; 
    12 int n,m;
    13 vector<int> tree[maxn];//
    14 int lost[maxn]={0},maxdep=0; 
    15 
    16 void DFS(int root,int depth)
    17  {
    18      if(depth>maxdep)maxdep=depth;
    19      if(tree[root].size()==0)//为叶子节点 
    20      {
    21          lost[depth]++; 
    22          return ;
    23      }
    24      for(int i=0;i<tree[root].size();i++)
    25      {
    26          DFS(tree[root][i],depth+1);
    27      }
    28     
    29  }
    30 int main(){
    31     scanf("%d %d",&n,&m);
    32     if(n==0){
    33     printf("0");
    34     return 0; 
    35     }
    36     for(int i=0;i<m;i++)
    37     {
    38         int id,count; 
    39         scanf("%d %d",&id,&count);
    40         for(int j=0;j<count;j++)
    41         {
    42             int tmp;
    43             scanf("%d",&tmp);
    44             tree[id-1].push_back(tmp-1); 
    45         }
    46          
    47     }
    48     //遍历树
    49      DFS(0,0); 
    50      printf("%d",lost[0]); 
    51      for(int i=1;i<=maxdep;i++)printf(" %d",lost[i]);
    52     return 0;
    53 }
  • 相关阅读:
    【FIRST USE】第一次用git把代码上传到github
    [多线程学习笔记] 一个线程安全的队列
    C中宏展开问题
    C语言中的命名空间
    c语言中赋值语句的结果
    Python一些难以察觉的错误
    C语言中的内存压缩技术
    简述数据结构:二叉查找树
    指针与指针的引用、指针的指针
    C++ 中的virtual关键词
  • 原文地址:https://www.cnblogs.com/ligen/p/4321244.html
Copyright © 2011-2022 走看看