题目详情 - 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();
}
}