使用三个数组分别记录每个人的父亲、母亲、性别id,然后使用bfs去搜索五代以内的祖先,如果另一个人五代以内的祖先与这个有重合,就输出Np,有个坑点,会导致测试点只通过两个,就是在存储的时候也要存下来父亲和母亲的性别。
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
typedef long long ll;
const int N = 1e5 + 10;
const int mod = 998244353;
int dad[N],mom[N],sex[N];
void solve() {
int n;
cin>>n;
memset(dad,-1,sizeof dad);
memset(mom,-1,sizeof mom);
for(int i = 0 ; i < n ; i++){
int id,fa,ma;
char gender;
cin>>id>>gender>>fa>>ma;
if(fa != -1) dad[id] = fa;
if(ma != -1) mom[id] = ma;
if(gender == 'M'){
sex[id] = 1;
}else{
sex[id] = 0;
}
}
int k;
cin>>k;
while(k--){
int x,y;
cin>>x>>y;
if(sex[x] == sex[y]){
cout<<"Never Mind"<<endl;
continue;
}
map<int,int> mp; //使用map记录每个人五辈的祖先
queue<pair<int,int>> q;
q.push({x,1});
while(q.size()){
int now = q.front().first;
int cnt = q.front().second;
mp[now] = 1;
q.pop();
if(mom[now] != -1 && cnt + 1 <= 5){
q.push({mom[now],cnt+1});
}
if(dad[now] != -1 && cnt + 1 <= 5){
q.push({dad[now],cnt+1});
}
}
bool flag = 0;
q.push({y,1});
while(q.size()){
int now = q.front().first;
int cnt = q.front().second;
if(mp[now] == 1){
cout<<"No"<<endl;
flag = 1;
break;
}
q.pop();
if(mom[now] != -1 && cnt + 1 <= 5){
q.push({mom[now],cnt+1});
}
if(dad[now] != -1 && cnt + 1 <= 5){
q.push({dad[now],cnt+1});
}
}
if(flag == 0) cout<<"Yes"<<endl;
}
}
signed main() {
// ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int tt = 1;
// cin >> tt;
while (tt--) {
solve();
}
return 0;
}