1004 Counting Leaves (30 分)

思路:并查集,建立家谱树,用数组root[]存储, used[]记录非叶节点,然后dfs查找每个节点的rank[], 查找过程可剪枝, 最后排序输出。

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 110;

typedef struct{
    int id;
    int r;
}Node;

int findrank(int x, int rank[], int root[]){
    if(x == 1) return 1;
    else if(rank[root[x]] != -1) return rank[x] = rank[root[x]] + 1;
    else return rank[x] = findrank(root[x], rank, root) + 1;
}

int cmp(Node n1, Node n2){
    return n1.r < n2.r;
}

int main(){
    int root[maxn], used[maxn], rank[maxn];
    Node node[maxn];
    int n, m, k, child;
    scanf("%d%d", &n, &m);
    fill(rank, rank+n, -1);
    memset(rank, -1, sizeof(rank));
    memset(used, 0, sizeof(used));
    if(n == 0) return 0;
    root[1] == 0; rank[1] = 1; node[1].id = 1;
    int top = 1, id;
    for(int i = 0; i < m; i++){
        scanf("%d%d", &id, &k);
        used[id] = 1;
        for(int j = 0; j < k; j++){
            scanf("%d", &child);
            root[child] = id;
            node[++top].id = child;
        }
    }
    for(int i = 1; i <= n; i++){
        node[i].r = findrank(node[i].id, rank, root);
    }
    sort(node+1, node+n+1, cmp);
    int p = 1, flag = 1;
    for(int r = 1; r <= n; r++){
        int cnt = 0;
        while(p <= n){
            if(node[p].r != r) break;
            else if(node[p].r == r && used[node[p].id] == 0) cnt++;
            p++;
        }
        printf("%s%d", flag ? "" : " ", cnt);
        if(p > n) break;
        if(r == 1) flag = 0;
    }
}

 

你可能感兴趣的:(PAT)