天梯赛:L2-016 愿天下有情人都是失散多年的兄妹 (25 分)

题目详情 - L2-016 愿天下有情人都是失散多年的兄妹 (25 分) (pintia.cn)

题解:对于每个给出的编号进行层序遍历,把遍历到的元素存进集合里。如果两个集合存在交集,就代表它们存在公共祖先,否则可以结婚。

不过感觉这个有点BUG,编号为0的情况貌似没有考虑到。

Code Segment:

#include<cstdio>
#include<set>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=1e5+1;
struct node{
    int father,mother;
    char sex;
}p[maxn];
void bfs(int id,set<int> &a)
{
    queue<int> q,e;
    int d,i;
    q.push(id);
    a.insert(id);
    for(i=0;i<4;i++)
    {
        while(!q.empty())
        {
            d=q.front();
            q.pop();
            if(p[d].father!=-1&&p[d].father)
            {
                a.insert(p[d].father);
                e.push(p[d].father);
            }
            if(p[d].mother!=-1&&p[d].mother)
            {
                a.insert(p[d].mother);
                e.push(p[d].mother);
            }
        }
        while(!e.empty())
        {
            q.push(e.front());
            e.pop();
        }
    }
}
int main()
{
    int n,k,id,a,b;
    set<int> s,t;
    vector<int> v;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%d",&id);
        getchar();
        scanf("%c%d%d",&p[id].sex,&p[id].father,&p[id].mother);
        if(p[id].father!=-1)
            p[p[id].father].sex='M';
        if(p[id].mother!=-1)
            p[p[id].mother].sex='F';
    }
    scanf("%d",&k);
    while(k--)
    {
        scanf("%d%d",&a,&b);
        if(p[a].sex==p[b].sex)
        {
            printf("Never Mind\n");
            continue;
        }
        bfs(a,s);
        bfs(b,t);
        set_intersection(s.begin(),s.end(),t.begin(),t.end(),inserter(v,v.begin()));
        if(v.size())
            printf("No\n");
        else
            printf("Yes\n");
        v.clear();
        s.clear();
        t.clear();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值