家谱处理 pta

这段代码使用C++实现了一个处理家谱关系的程序,支持查找父子、兄弟、子孙和先祖关系。通过读取人物名字和关系类型,判断两个家庭成员之间的关系是否成立。
//可以用树处理
//可以用结构图处理
//重点处理 各种关系


#include<bits/stdc++.h>
using namespace std;

struct node
{
    char data[20];
    int num,parent;
} tree[1010];

int main()
{
    char name[1250],a[20];
    int n,m,l,x,k;
    scanf("%d %d",&n,&m);
    getchar();
    for(int i=0; i<n; i++)
    {
        gets(name);
        l=strlen(name);
        x=k=0;
        for(int j=0; j<l; j++)
        {
            if(name[j]==' ')
                x++;
            else
                a[k++]=name[j];
        }
        a[k]='\0';
        strcpy(tree[i].data,a);
        tree[i].num=x;
    }
    char w[10][20];
    while(m--)
    {
        for(int i=0; i<6; i++)
        {
            scanf("%s",w[i]);
        }
        int p,q,x1,x2;
        for(int i=0; i<n; i++)
        {
      &nbs
### PTA 家谱处理的算法与数据结构实现 在家谱处理问题中,核心目标是对家族成员之间的父子关系进行有效存储和查询。通过分析引用内容[^1]、[^2]以及[^3],可以得出以下结论: #### 1. 数据结构的选择 为了高效地表示家谱中的父子关系,通常采用如下几种方式之一: - **数组**:使用 `father[]` 数组来保存每个人的父节点编号。例如,`father[i] = j` 表示第 i 号人的父亲是第 j 号人[^2]。 - **哈希表**:如果需要频繁查找某个人的名字对应其唯一 ID,则可以通过哈希表快速完成映射操作。 #### 2. 编号机制 为了避免字符串比较带来的性能开销,可先给所有人分配唯一的整数ID。具体法是从输入的数据集中依次读取姓名并赋予连续递增的索引值作为该个体的身份标识符[^1]^。 #### 3. 层次计算逻辑 当被询问到某个特定人物位于哪一层级时(即距离根节点有多远),可通过不断追溯其祖先直至到达始祖为止,在此过程中累计经过了几代即可得知当前角色处于整个族系图里的哪个位置上^。 以下是基于以上描述的一个可能实现方案: ```python MAXN = 10005 # 假设最多有这么多人 name_to_id = {} id_to_name = [""] * MAXN depth = [-1] * MAXN fa = [-1] * MAXN def preprocess(names, relations): global name_to_id, id_to_name, depth, fa cnt = 0 for name in names: if name not in name_to_id: name_to_id[name] = cnt id_to_name[cnt] = name cnt += 1 for child,parent in relations: cid = name_to_id[child] pid = name_to_id[parent] fa[cid]=pid def calc_depth(root_idx): stack=[root_idx] depth[root_idx]=0 while(stack): cur=stack.pop() for idx,dad in enumerate(fa): if dad==cur and depth[idx]==-1 : depth[idx]=depth[cur]+1 stack.append(idx) names=["John","Robert","Frank","Andrew","Nancy","David"] relations=[("Robert","John"), ("Frank","Robert"), ("Andrew","John"), ("Nancy","Robert"), ("David","Nancy")] preprocess(names,relations) calc_depth(name_to_id["John"]) for n in names: nid=name_to_id[n] print("{} is at level {}".format(n,depth[n])) ``` 上述代码片段展示了如何预处理名称列表及其关联关系,并利用栈结构迭代求解各结点所在层数的方法[^2]^。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值