【1004】Counting Leaves (30 分)

简介: 【1004】Counting Leaves (30 分)【1004】Counting Leaves (30 分)
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>  
#include<map>
#include<vector>
#include<queue> 
using namespace std;
const int N=110;
vector<int> G[N]; //存放树
int leaf[N]={0}; //存放每层的叶子结点个数
int max_h=1;  //树的深度
void DFS(int index,int h){ //index为当前遍历到的结点编号 h为当前的深度
  max_h=max(h,max_h); //记录树maxh,便于后面遍历输出每层节点数
  if(G[index].size() == 0){ //如果该结点是叶子结点
    leaf[h]++;
    return;
  }
  for(int i=0;i<G[index].size();i++) { //枚举所有子结点
    DFS(G[index][i],h+1);
  }
}
int main(){   
  int n,m,parent,child,k;
  scanf("%d%d",&n,&m);//结点数 非叶子结点数
  for(int i=0;i<m;i++){
    scanf("%d%d",&parent,&k); //父结点编号及子结点个数
    for(int j=0;j<k;j++){
      scanf("%d",&child); //子结点编号
      G[parent].push_back(child); //加边
    }
  }
  DFS(1,1);//根结点编号为1 及其h=1
  printf("%d",leaf[1]); 
  for(int i=2;i<=max_h;i++)  printf(" %d",leaf[i]);
  system("pause"); 
    return 0;   
}
相关文章
|
机器学习/深度学习 存储 C++
【PAT甲级 - C++题解】1004 Counting Leaves
【PAT甲级 - C++题解】1004 Counting Leaves
71 0
|
C++
【PAT甲级 - C++题解】1145 Hashing - Average Search Time
【PAT甲级 - C++题解】1145 Hashing - Average Search Time
83 0
|
存储 C++
【PAT甲级 - C++题解】1115 Counting Nodes in a Binary Search Tree
【PAT甲级 - C++题解】1115 Counting Nodes in a Binary Search Tree
76 0
LeetCode 433. Minimum Genetic Mutation
现在给定3个参数 — start, end, bank,分别代表起始基因序列,目标基因序列及基因库,请找出能够使起始基因序列变化为目标基因序列所需的最少变化次数。如果无法实现目标变化,请返回 -1。
68 0
LeetCode 433. Minimum Genetic Mutation
PAT甲级 1004. Counting Leaves(30分)
PAT甲级 1004. Counting Leaves(30分)
67 0
|
人工智能 BI
AtCoder Beginner Contest 216 F - Max Sum Counting (降维 背包dp)
AtCoder Beginner Contest 216 F - Max Sum Counting (降维 背包dp)
134 0
|
人工智能
codeforces 1092——F:Tree with Maximum Cost (树上DP)
codeforces 1092——F:Tree with Maximum Cost (树上DP)
118 0
PAT (Advanced Level) Practice - 1004 Counting Leaves(30 分)
PAT (Advanced Level) Practice - 1004 Counting Leaves(30 分)
109 0
Data Structures and Algorithms (English) - 6-17 Shortest Path [4](25 分)
Data Structures and Algorithms (English) - 6-17 Shortest Path [4](25 分)
109 0
Data Structures and Algorithms (English) - 6-11 Shortest Path [1](25 分)
Data Structures and Algorithms (English) - 6-11 Shortest Path [1](25 分)
114 0