1004 Counting Leaves (30 point(s))

1004 Counting Leaves (30 point(s))

A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.

Example:

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

using namespace std;

struct Elem {
    int ID;
    int Level;
};

void Print(int Level, int Count)
{
    cout << (Level==1?"":" ") << Count;
}

int main()
{
    int N, M;
    cin >> N >> M;
    map<int, vector<int>> T;
    for(int i = 0; i < M; i++) {
        int ID, K;
        cin >> ID >> K;
        vector<int> IDK(K);
        for(int k = 0; k < K; k++)
            cin >> IDK[k];
        T.emplace(ID, IDK);
    }
    if(N == 0) return 0;
    queue<Elem> Q;
    Q.push({1,1});
    int no_chlid = 0;
    int last_level = 1;
    while(!Q.empty()) {
        Elem &temp = Q.front();
        if(last_level != temp.Level) {
            Print(last_level, no_chlid);
            last_level = temp.Level;
            no_chlid = 0;
        }
        if(T[temp.ID].empty()) {
            no_chlid += 1;
        } else {
            for(auto &x : T[temp.ID])
                Q.push({x, temp.Level+1});
        }
        Q.pop();
    }
    Print(last_level, no_chlid);
}

思路:

利用队列,层次遍历树,入队同时标记所属层次Level,然后就可以根据 Level 区分统计该层没有子节点的个数。

猜你喜欢

转载自blog.csdn.net/u012571715/article/details/113888873