L2-016 願天下有情人都是失散多年的兄妹 (25 分)
呵呵。大家都知道五服以內不得通婚,即兩個人最近的共同祖先如果在五代以內(即本人、父母、祖父母、曾祖父母、高祖父母)則不可通婚。本題就請你幫助一對有情人判斷一下,他們究竟是否可以成婚?
輸入格式:
輸入第一行給出一個正整數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
輸出樣例:
Never Mind
Yes
Never Mind
No
Yes
No
Yes
No
No
注意:在錄入數據的時候需要記錄父母的性別,萬一再婚呢?(測試點1、3、4)
#include<iostream>
#include<vector>
#include<string>
#include<map>
using namespace std;
int result;
struct Person {
int sex;
vector<int> parent;
};
map<int, Person> people;
void judge(int start, int end, int len) {
if (start == end)
result = 1;
if (len<4)
for (auto &i: people[start].parent)
for (auto &j: people[end].parent)
judge(i, j, len + 1);
}
int main() {
int n, m, id, father, mother;
char sex;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> id >> sex >> father >> mother;
people[id].sex=sex=='M' ? 1 : 0 ;
people[father].sex = 1;
if (father != -1)
people[id].parent.push_back(father);
if (mother != -1)
people[id].parent.push_back(mother);
}
cin >> m;
for (int i = 0; i < m; i++) {
cin >> father >> mother;
if (people[father].sex == people[mother].sex)
cout << "Never Mind" << endl;
else {
result = 0;
judge(father, mother, 0);
cout << (result ? "No" : "Yes") << endl;
}
}
return 0;
}