[PAT (Advanced Level) ]1004. Counting Leaves解题文档

1004. Counting Leaves (30)


时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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)输入数据,并标记下哪些不是叶子节点;
(2)处理数据成矩阵形式;
(3)用BFS算法求得每个节点到root的距离;
(4)综合分析,输出结果。

容易遗忘的情形:
笔者就是这里出错,没有考虑到M=0的情形,因为M=0的时候,不需要任何计算,直接输出“1”即可。


给出C++代码。
#include<iostream>
#include<string>
#include<cstdlib>

using namespace std;
int N,M;
string* ID=new string[101];
int matrix[101][101];
bool isLeafNode[101];
bool isNode[101];
int number[101];
int maxDistance=0;

void input(){
    cin>>N>>M;
    for(int i=0;i<101;i++){
        for(int j=0;j<101;j++)
            matrix[j][i]=0;
        isLeafNode[i]=true;
        isNode[i]=false;
        number[i]=0;
    }
    for(int i=0;i<M;i++){
        int K;
        string root;
        cin>>root>>K;
        for(int j=0;j<K;j++){
            cin>>ID[j];
        }
        int rootk=atoi(root.c_str());
        for(int j=0;j<K;j++){
            matrix[rootk-1][atoi(ID[j].c_str())-1]=1;
            isLeafNode[rootk-1]=false;
            isNode[atoi(ID[j].c_str())-1]=true;
        }
    }
}

void Distance(int I,int length){
    number[I]=length;
    if(length>maxDistance)
        maxDistance=length;
    for(int i=0;i<100;i++){
        if(matrix[I][i]!=0){
            Distance(i,length+1);
        }
    }
}


int main(){
    input();
    if(M==0){
        cout<<N;
    }
    else{
    Distance(0,0);
    for(int i=0;i<maxDistance+1;i++){
        int numb=0;
        for(int j=0;j<100;j++){
         if(isLeafNode[j]==true&&number[j]==i&&isNode[j]==true)
             numb++;
        }
        if(maxDistance==i)
            cout<<numb;
        else
            cout<<numb<<" ";
    }}
    return 0;
}

测试情况:
[PAT (Advanced Level) ]1004. Counting Leaves解题文档_第1张图片

你可能感兴趣的:([PAT (Advanced Level) ]1004. Counting Leaves解题文档)