1004 Counting Leaves(dfs)

本文介绍了一个算法问题,即如何通过递归深度优先搜索(DFS)的方法来统计家谱树中没有子节点的家庭成员数量。输入包括家谱树的结构,输出则是各层级上无子女成员的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

标明出处:https://www.liuchuo.net/archives/2229
1004 Counting Leaves(30 分)

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

#include <cstdio>
#include <vector>

using namespace std;
vector<int> v[100];
int book[100], maxdepth = -1;
void dfs(int index, int depth){
    if(v[index].size() == 0){
        book[depth]++;
        maxdepth = max(maxdepth, depth);
        return ;
    }
    for(int i = 0; i < v[index].size(); i++){
        dfs(v[index][i], depth+1);
    }
}
int main(){
    int n, m, k, node, c;
    scanf("%d %d", &n, &m);
    for(int i = 0; i < m; i++){
        scanf("%d %d", &node, &k);
        for(int j = 0; j < k; j++){
            scanf("%d", &c);
            v[node].push_back(c);
        }
    }
    dfs(1, 0);
    printf("%d", book[0]);
    for(int i = 1; i <= maxdepth; i++)
        printf(" %d", book[i]);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值