用c++书写这个程序:呵呵。大家都知道五服以内不得通婚即两个人最近的共同祖先如果在五代以内即本人、父母、祖父母、曾祖父母、高祖父母则不可通婚。本题就请你帮助一对有情人判断一下他们究竟是否可以成婚?输入格式:输入第一行给出一个正整数N2 ≤ N ≤10 4 随后N行每行按以下格式给出一个人的信息:本人ID 性别 父亲ID 母亲ID其中ID是5位数字每人不同;性别M代表男性、F代表女性。如果某人的父亲
#include
using namespace std;
struct Person { string id; char gender; string fatherId; string motherId; };
unordered_map<string, Person> people;
bool isAncestor(string ancestorId, string personId, int generation) { if (generation > 5) { return false; } if (ancestorId == personId) { return true; } Person person = people[personId]; if (person.fatherId != "-1" && isAncestor(ancestorId, person.fatherId, generation + 1)) { return true; } if (person.motherId != "-1" && isAncestor(ancestorId, person.motherId, generation + 1)) { return true; } return false; }
bool canMarry(string person1Id, string person2Id) { Person person1 = people[person1Id]; Person person2 = people[person2Id]; if (person1.gender == person2.gender) { return false; } if (isAncestor(person1Id, person2Id, 0) || isAncestor(person2Id, person1Id, 0)) { return false; } return true; }
int main() { int N; cin >> N; for (int i = 0; i < N; i++) { string id, fatherId, motherId; char gender; cin >> id >> gender >> fatherId >> motherId; Person person; person.id = id; person.gender = gender; person.fatherId = fatherId; person.motherId = motherId; people[id] = person; } int K; cin >> K; for (int i = 0; i < K; i++) { string person1Id, person2Id; cin >> person1Id >> person2Id; if (canMarry(person1Id, person2Id)) { cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0;
原文地址: http://www.cveoy.top/t/topic/hTy4 著作权归作者所有。请勿转载和采集!