题目:
呵呵。大家都知道五服以内不得通婚,即两个人最近的共同祖先如果在五代以内(即本人、父母、祖父母、曾祖父母、高祖父母)则不可通婚。本题就请你帮助一对有情人判断一下,他们究竟是否可以成婚?
输入格式:
输入第一行给出一个正整数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
解析 :
将输入数据存入一个map映射(模拟内存结构)中(注意要把父母的信息也要存入map映射里),然后分别遍历两个情侣的五层二叉树,把遍历的所有节点存入集合中(ID为-1则不存)的同时用count记下集合被插入次数,如果集合被插入次数(count)大于集合元素,说明集合被插入了重复元素,那么五服里有血亲。
代码:
#include<set>
#include<iostream>
#include<unordered_map>
class Person {
public:
Person()= default;
Person(char p_sex,const std::string& p_fatherID,const std::string& p_motherID)
:sex(p_sex),fatherID(p_fatherID),motherID(p_motherID)
{}
char sex;
std::string fatherID;
std::string motherID;
};
void addPerson(std::set<std::string>& set,std::unordered_map<std::string,Person>& map,std::string& ID,int length,int& count) {
if (length == 0) {
return;
}
if (ID != "-1") {
count++;
set.insert(ID);
}
if (map.find(ID) != map.end()) {
addPerson(set,map,map[ID].fatherID,length-1,count);
addPerson(set,map,map[ID].motherID,length-1,count);
}
}
int main() {
int N;
std::cin>>N;
char sex;
std::unordered_map<std::string,Person> map;
while (N--) {
std::string ID,motherID,fatherID;
char sex;
std::cin>>ID>>sex>>fatherID>>motherID;
map[ID] = Person(sex,fatherID,motherID);
if (map.find(fatherID)==map.end()) {
map[fatherID] = Person('M',"-1","-1");
}
if (map.find(motherID)==map.end()) {
map[motherID] = Person('F',"-1","-1");
}
}
int K;
std::cin>>K;
while (K--) {
std::string firstID,secondID;
std::set<std::string> set;
std::cin>>firstID>>secondID;
if (map[firstID].sex == map[secondID].sex) {
std::cout<<"Never Mind"<<std::endl;
} else {
int count = 0;
addPerson(set,map,firstID,5,count);
addPerson(set,map,secondID,5,count);
if (set.size()<count) {
std::cout<<"No"<<"\n";
}else {
std::cout<<"Yes"<<"\n";
}
}
}
}
测试结果: