PAT甲级1004
题目:
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.
Input Specification:
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.
The input ends with N being 0. That case must NOT be processed.
Output Specification:
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
题目大意:给出总结点n和非叶子节点m,接下来每行给出第i个非叶子节点的孩子数,求每层的叶子节点数。这题BFS和DFS都可以,之前都是用的DFS这里换个BFS做。首先要两次循环,第二次记录每个节点所在的层数,然后从根节点1开始依次进队,定义全局数组nonleaf记录每层的叶子节点,BFS遍历碰到叶子节点即让该层的nonleaf+1。注意:要有个max判断最高层数,不然要多循环很多次浪费时间,max初始值必须为1!!!因为有只有一个节点的情况
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct node{
int height;
vector<int> child;
};
node nd[100];
vector<int> nonLeaf(100);
void BFS(int root){
queue<int> q;
q.push(root);
while(!q.empty()){
int nod=q.front();
q.pop();
if(nd[nod].child.size()!=0){
for(int i=0;i<nd[nod].child.size();i++){
nd[nd[nod].child[i]].height=nd[nod].height+1;
q.push(nd[nod].child[i]);
}
}else{
nonLeaf[nd[nod].height]++;
}
}
}
int main(){
int n,m,index,ch,tmp,max=1;
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++){
scanf("%d%d",&index,&tmp);
for(int j=0;j<tmp;j++){
scanf("%d",&ch);
nd[index].child.push_back(ch);
}
}
nd[1].height=1;
queue<int> q;
q.push(1);
while(!q.empty()){
int nod=q.front();
q.pop();
if(nd[nod].child.size()!=0){
for(int i=0;i<nd[nod].child.size();i++){
nd[nd[nod].child[i]].height=nd[nod].height+1;
if(max<nd[nd[nod].child[i]].height) max=nd[nd[nod].child[i]].height;
q.push(nd[nod].child[i]);
}
}
}
BFS(1);
for(int i=1;i<=max;i++){
if(i!=1) printf(" ");
printf("%d",nonLeaf[i]);
}
system("pause");
return 0;
}