深搜,第一个人的五代以内的祖先不在第二个人的五代以内的祖先,输出yes,控制一下dfs的层数
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
const int maxn = 100005;
int father[maxn],mother[maxn],sex[maxn];
bool vis[maxn],flag;
void dfs(int now,int step,int f)
{
if(step == 5 || !flag)
return ;
//第一个人的五代以内的祖先存在
if(f == 1 && now!= -1 && step)
vis[now] = 1;
//如果第二个人五代以内的祖先是第一个五代以内的祖先
if(f == 2 && vis[now] && now != -1)
{
flag = false;
return ;
}
int fu = father[now];
int mu = mother[now];
//两条分支,往长辈找
if(now != -1 && fu != -1)
dfs(fu,step + 1,f);
if(now != -1 && mu != -1)
dfs(mu,step + 1,f);
}
int main()
{
int n,id,fid,mid;
char msex;
cin >> n;
memset(father,-1,sizeof(father));
memset(mother,-1,sizeof(mother));
memset(sex,-1,sizeof(sex));
for (int i = 0; i < n; ++i)
{
cin >> id >> msex >> fid >> mid;
if(msex == 'M')
sex[id] = 1;
else
sex[id] = 0;
father[id] = fid;
mother[id] = mid;
if(fid != -1)
sex[fid] = 1;
if(mid != -1)
sex[mid] = 0;
}
int m;
cin >> m;
for (int i = 0; i < m; ++i)
{
int x,y;
cin >> x >> y;
if(sex[x] == sex[y])
printf("Never Mind\n");
else
{
memset(vis,false,sizeof(vis));
flag = true;
dfs(x,0,1);
dfs(y,0,2);
if(flag)
printf("Yes\n");
else
printf("No\n");
}
}
}