编写一个C++代码两个人最近的共同祖先如果在五代以内即本人、父母、祖父母、曾祖父母、高祖父母则不可通婚。本题就请你帮助一对有情人判断一下他们究竟是否可以成婚?输入格式:输入第一行给出一个正整数N2 ≤ N ≤10 4 随后N行每行按以下格式给出一个人的信息:本人ID 性别 父亲ID 母亲ID其中ID是5位数字每人不同;性别M代表男性、F代表女性。如果某人的父亲或母亲已经不可考则相应的ID位置上标记
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;
struct Person {
string id;
char gender;
string father;
string mother;
};
unordered_map<string, Person> people;
bool isAncestor(const string& id1, const string& id2) {
if (id1 == id2) {
return true;
}
if (id1 == "-1" || id2 == "-1") {
return false;
}
const Person& person = people[id1];
return isAncestor(person.father, id2) || isAncestor(person.mother, id2);
}
bool isWithinFiveGenerations(const string& id1, const string& id2) {
if (id1 == id2) {
return true;
}
if (id1 == "-1" || id2 == "-1") {
return false;
}
const Person& person = people[id1];
if (isAncestor(person.father, id2) || isAncestor(person.mother, id2)) {
return true;
}
return isWithinFiveGenerations(person.father, id2) || isWithinFiveGenerations(person.mother, id2);
}
int main() {
int N;
cin >> N;
for (int i = 0; i < N; i++) {
Person person;
cin >> person.id >> person.gender >> person.father >> person.mother;
people[person.id] = person;
}
int K;
cin >> K;
for (int i = 0; i < K; i++) {
string id1, id2;
cin >> id1 >> id2;
if (people[id1].gender == people[id2].gender) {
cout << "Never Mind" << endl;
} else if (isWithinFiveGenerations(id1, id2)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/h49c 著作权归作者所有。请勿转载和采集!