【PAT 1005 The Largest Generation (25)】& 树 & dfs

本文介绍了一种通过递归深度优先搜索算法来解决寻找家族树中人口最多的代的问题。输入包含家庭成员总数及各成员之间的关系,输出人口最多的代及其人数。

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

题目描述
A family hierarchy is usually presented by a pedigree tree where all the nodes on the same level belong to the same generation. Your task is to find the generation with the largest population.

输入描述:
Each input file contains one test case. Each case starts with two positive integers N (<100) which is the total number of family members in the tree (and hence assume that all the members are numbered from 01 to N), and M (

#include<cstdio>
#include<cmath>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX = 1e2 + 10;
typedef long long LL;
vector <int> v[MAX];
int vis[MAX],o[MAX],ans,sum,cut;
void dfs(int f,int u){
    if(vis[f]) return ;
    vis[f] = 1; o[u]++;
    for(int i = 0; i < v[f].size(); i++)
        dfs(v[f][i],u + 1);
}
int main()
{
    int n,m;
    scanf("%d %d",&n,&m);
    while(m--){
        int o,u,p;
        scanf("%d %d",&o,&u);
        while(u--){
            scanf("%d",&p);
            v[o].push_back(p);
        }
    }
    ans = sum = 0;
    for(int i = 1; i <= n; i++)
        if(!vis[i])
            dfs(i,1);
    for(int i = 1; i <= n; i++)
        if(o[i] > ans) ans = o[i],sum = i;
    printf("%d %d\n",ans,sum);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值