7-27 家谱处理 (并查集)

分析

5种关系:

  1. X is a child of Y (fa[x]==y)
  2. X is the parent of Y (fa[y]==x)
  3. X is a sibling of Y (fa[x]==fa[y])
  4. X is a descendant of Y (fa[fa[…fa[x]]]=y)
  5. X is an ancestor of Y (fa[fa[…fa[y]]]=x)

只需要将父辈和孩子间的关系存储下来就可以了。

C++ 代码
#include<bits/stdc++.h>
using namespace std;
int n,m,fa[110];
vector<int> s[110];  //s[i]存储第i辈所有人的信息
map<string,int> mp;
int main()
{
    for(int i=0;i<110;i++) fa[i]=i;
    cin>>n>>m;
    getchar();
    string nl;
    for(int i=1;i<=n;i++)
    {
        getline(cin,nl);
        int co=0;
        for(int j=0;j<nl.size();j++)
        {
            if(nl[j]==' ') co++;    
        }
        if(!co) fa[i]=0;    //该人为所有人的祖先
        else{
            int len=s[co/2].size(); 
            fa[i]=s[co/2][len-1];   //该人的父辈为上一辈的最后一个人
        }
        s[co/2+1].push_back(i);
        mp[nl.substr(co)]=i;    //该人的序号为i
    }
    string q;
    for(int i=1;i<=m;i++)
    {
       getline(cin,q);
       stringstream ssin(q);
       vector<string> temp;
       while(ssin>>q) temp.push_back(q);
       int a=mp[temp[0]],b=mp[temp[5]];
       int f=0;
       if(a==b){    //两个人都是自己,不能做判断,直接continue
           puts("False");
           continue;
       }
       if(temp[3]=="child"){
           if(fa[a]==b) f=1;
       }
       if(temp[3]=="parent"){
           if(fa[b]==a) f=1;
       }
       if(temp[3]=="descendant"){
          while(a!=0){
              if(a==b) f=1;
              a=fa[a];
           }
       }
       if(temp[3]=="ancestor"){
          while(b!=0){
              if(b==a) f=1;
              b=fa[b];
          }
       }
       if(temp[3]=="sibling"){
           if(fa[a]==fa[b]) f=1;
       }
       if(f) puts("True");
       else puts("False");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Jay_fearless

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

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

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

打赏作者

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

抵扣说明:

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

余额充值