PAT---1004 Counting Leaves(树,未AC)

题意:要输出每一层的叶子结点的个数,若这一层叶子结点个数为0, 输出0。
解题思路:按照输入顺序记录每一个结点的层数,并用一个vector来存储其孩子,若vector的大小为0,则说明其实叶子结点。
但是有两个样例未通过。。。。。

#include <iostream>
#include <vector>
#include <map>

using namespace std;

struct Node
{
    int num, floor;
};

vector<Node> nodelist[101];
map<int, int> dict;

int list[101];     //表示结点i的层数

int main()
{
    int n, m;
    cin >> n >> m;
    int id, k, child, maxfloor = 1;
    Node tmp;
    list[1] = 1;   //根节点的层数固定为1
    while(m--)
    {
        cin >> id >> k;
        for(int i = 0; i < k; i++)
        {
            cin >> child;
            tmp.num = child;
            tmp.floor = list[id]+1;
            list[tmp.num] = tmp.floor;
            nodelist[id].push_back(tmp);
            if(maxfloor < tmp.floor)   //记录树的最大层数
                maxfloor = tmp.floor;
        }
    }
    //按照结点编号遍历,记录每一层叶子结点个数
    for(int i = 1; i <= n; i++)
        if(nodelist[i].size() == 0)
            dict[list[i]]++;
    for(int i = 1; i <= maxfloor; i++)
        if(i == 1)
            cout << dict[i];
        else
            cout << " " << dict[i];
    cout << endl;

    return 0;
}

/*
15 5
1 3 2 3 4
2 2 5 6
4 2 7 8
5 3 9 10 11
7 4 12 13 14 15
*/

/*
7 3
1 2 2 3
2 2 4 5
3 2 6 7
*/

猜你喜欢

转载自blog.csdn.net/mch2869253130/article/details/88072947