L2-016. 愿天下有情人都是失散多年的兄妹
呵呵。大家都知道五服以内不得通婚,即两个人最近的共同祖先如果在五代以内(即本人、父母、祖父母、曾祖父母、高祖父母)则不可通婚。本题就请你帮助一对有情人判断一下,他们究竟是否可以成婚?
输入格式:
输入第一行给出一个正整数N(2 <= N <= 104),随后N行,每行按以下格式给出一个人的信息:
本人ID 性别 父亲ID 母亲ID
其中ID是5位数字,每人不同;性别M代表男性、F代表女性。如果某人的父亲或母亲已经不可考,则相应的ID位置上标记为-1。
接下来给出一个正整数K,随后K行,每行给出一对有情人的ID,其间以空格分隔。
注意:题目保证两个人是同辈,每人只有一个性别,并且血缘关系网中没有乱伦或隔辈成婚的情况。
输出格式:
对每一对有情人,判断他们的关系是否可以通婚:如果两人是同性,输出“Never Mind”;如果是异性并且关系出了五服,输出“Yes”;如果异性关系未出五服,输出“No”。
输入样例:24 00001 M 01111 -1 00002 F 02222 03333 00003 M 02222 03333 00004 F 04444 03333 00005 M 04444 05555 00006 F 04444 05555 00007 F 06666 07777 00008 M 06666 07777 00009 M 00001 00002 00010 M 00003 00006 00011 F 00005 00007 00012 F 00008 08888 00013 F 00009 00011 00014 M 00010 09999 00015 M 00010 09999 00016 M 10000 00012 00017 F -1 00012 00018 F 11000 00013 00019 F 11100 00018 00020 F 00015 11110 00021 M 11100 00020 00022 M 00016 -1 00023 M 10012 00017 00024 M 00022 10013 9 00021 00024 00019 00024 00011 00012 00022 00018 00001 00004 00013 00016 00017 00015 00019 00021 00010 00011
可以将关系看做一个有向图,进行BFS。建好后对,对没对情侣a,b分别遍历,bool型数组check用来判断五服内是否有公共的。对a遍历时,将遍历到的置1,对b遍历时遇到check为1,则ans=false。
判断:先看性别,不同时看ans
注意:
1.题目只给了部分人的父母id,有些人的父母id没给,对于这些人,不要求其父母,因为他们的父母id是不确定的。处理方法:一种是限制他们找父母,另一种时初始化所有人父母为-1,再读入,这样可避免。(养成良好的初始化的习惯可以避免某些麻烦)
2.读取到父母id时候,要顺便确认父母性别,否则查询非孩子的结点之间关系时,不能正常判断性别关系。
#include <cstdio>
#include <queue>
using namespace std;
const int MAX = 100000;
struct Person{
int left, right, h;
char sex;
Person(){
left = right = -1;
h = 1;
}
}per[MAX];
int n, k;
bool judge[MAX] = {false}, check[MAX] = {false}, ans, flag;
void BFS(int x){
queue<int> q;
q.push(x);
per[x].h = 1;
judge[x] = true;
while(!q.empty()){
int front = q.front();
q.pop();
if(flag) check[front] = true;
else{
if(check[front] == true){
ans = false;
}
}
if(per[front].left != -1 && per[front].h <= 4){
int v = per[front].left;
per[v].h = per[front].h+1;
if(!judge[v]){
q.push(v);
judge[v] = true;
}
}
if(per[front].right != -1 && per[front].h <= 4){
int v = per[front].right;
per[v].h = per[front].h+1;
if(!judge[v]){
q.push(v);
judge[v] = true;
}
}
}
}
int main(){
scanf("%d", &n);
for(int i = 0; i < n; i++){
int id, l, r;
char sex;
scanf("%d %c %d %d", &id, &sex, &l, &r);
per[id].sex = sex;
per[id].left = l;
per[id].right = r;
per[l].sex = 'M';
per[r].sex = 'F';
}
scanf("%d", &k);
while(k--){
int a, b;
scanf("%d %d", &a, &b);
if(per[a].sex == per[b].sex) printf("Never Mind\n");
else{
ans = true, flag = true;
fill(judge, judge+MAX, false);
fill(check, check+MAX, false);
BFS(a);
fill(judge, judge+MAX, false);
flag = false;
BFS(b);
if(ans) printf("Yes\n");
else printf("No\n");
}
}
return 0;
}