题目意思很清晰,就是找出五代以内是否有相同的祖先
可以创建一个结构,直接用结构数组进行判断
直接上代码,简单易懂。
#include<stdio.h>
typedef struct Node
{
int sex;//0代表女,1代表男
int mother;
int father;
}Node;
Node s[120000];
void init()
{
int i;
for(i=0;i<=120000;i++)
{
s[i].mother=s[i].father=-1;
}
}
int Judge(int a,int b)
{
int k,l;
k=l=0;
int r,t;
r=t=0;
int j,i;
int p[10000];
int o[10000];
p[0]=a;
o[0]=b;
int e=4;
while(e--)
{
for(i=0;i<=k;i++)
{
if(s[p[i]].mother!=-1)
p[++r]=s[p[i]].mother;
if(s[p[i]].father!=-1)
p[++r]=s[p[i]].father;
}
k=r;
for(i=0;i<=l;i++)
{
if(s[o[i]].mother!=-1)
o[++t]=s[o[i]].mother;
if(s[o[i]].father!=-1)
o[++t]=s[o[i]].father;
}
l=t;
}
for(i=0;i<=k;i++)
{
for(j=0;j<=l;j++)
{
if(p[i]==o[j])
return 1;
}
}
return 0;
}
int main()
{
int n,i,j,k;
scanf("%d",&n);
int z,f,m;
char x;
init();
while(n--)
{
scanf("%d %c%d%d",&z,&x,&f,&m);
if(x=='F')
s[z].sex=0;
else if(x=='M')
s[z].sex=1;
s[z].mother=m;
s[z].father=f;
if(f!=-1)
s[f].sex=1;
if(m!=-1)
s[m].sex=0;
}
scanf("%d",&k);
while(k--)
{
int a,b;
scanf("%d%d",&a,&b);
if(s[a].sex==s[b].sex)
{
printf("Never Mind\n");
continue;
}
int t=Judge(a,b);
if(t==1)
printf("No\n");
else
printf("Yes\n");
}
return 0;
}