数据结构与算法题目集(中文) - 7-27 家谱处理(30 分)

本文介绍了一种使用C++解决家族树中节点间关系判断的方法。通过输入节点的缩进级别来确定父子关系,并实现了判断两个节点是否为父子、兄弟、后代与祖先等关系的功能。文章提供了一个完整的代码实现,包括节点结构定义、关系判断函数及主函数流程。

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

题目链接:点击打开链接

题目大意:略。

解题思路:略。

AC 代码

#include<bits/stdc++.h>
#include<cmath>

#define mem(a,b) memset(a,b,sizeof a);
#define INF 0x3f3f3f3f

using namespace std;

typedef long long ll;

struct cmp
{
    bool operator()(const char* s1,const char* s2) const
    {
        return strcmp(s1,s2)<0; // default:map 根据 key 排序(字典序)
    }
};

map<char*,int,cmp> mp;

struct node
{
    char name[20];
    int par,space;
}*tree;

int n,m;

int calSp(char name[])
{
    char c;
    int cnt=0,k=0;
    while((c=getchar())==' ') cnt++;

    do
    {
        name[k++]=c;
    }while((c=getchar())!='\n');
    name[k]='\0';

    return cnt;
}

// 往前遍历第一个比他缩进少的就是他的父亲,否则就是亚当夏娃
int trace(int child)
{
    for(int i=child-1;i>=0;i--)
        if(tree[i].space<tree[child].space) return i;

    return -1;
}

int jde_child_parent(int aid, int bid)
{
    if(tree[aid].par==aid) tree[aid].par=trace(aid);
    return tree[aid].par==bid;
}

int jde_sibling(int aid, int bid)
{
    if(tree[aid].par==aid) tree[aid].par=trace(aid);
    if(tree[bid].par==bid) tree[bid].par=trace(bid);
    return tree[aid].par==tree[bid].par;
}

int jde_desce_ancest(int aid, int bid)
{
    while(aid!=-1)
        if(jde_child_parent(aid,bid)) return 1;
        else aid=tree[aid].par;

    return 0;
}

void solve()
{
    char a[20],with[20],b[20];
    scanf("%s%*s%*s%s%*s%s",a,with,b);

    int rs,aid=mp[a],bid=mp[b];
    char op=with[0];
    if(op=='c') rs=jde_child_parent(aid,bid);
    else if(op=='p') rs=jde_child_parent(bid,aid);
    else if(op=='s') rs=jde_sibling(aid,bid);
    else if(op=='d') rs=jde_desce_ancest(aid,bid);
    else if(op=='a') rs=jde_desce_ancest(bid,aid);

    puts(rs?"True":"False");
}

int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        mp.clear();
        tree=(node*)malloc(sizeof(node)*n);
        getchar();

        for(int i=0;i<n;i++)
        {
            tree[i].space=calSp(tree[i].name);
            tree[i].par=i; // init
            mp[tree[i].name]=i;
        }
        tree[0].par=-1;

        for(int i=0;i<m;i++) solve();
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陆克和他的代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值