一直过不去,不知道为啥,在本地一点问题都没有。。。
思路是递归求解
题目描述: 如果A,B是C的父母亲,则A,B是C的parent,C是A,B的child,如果A,B是C的(外)祖父,祖母,则A,B是C的grandparent,C是A,B的grandchild,如果A,B是C的(外)曾祖父,曾祖母,则A,B是C的great-grandparent,C是A,B的great-grandchild,之后再多一辈,则在关系上加一个great-。
输入描述:
输入包含多组测试用例,每组用例首先包含2个整数n(0<=n<=26)和m(0<m<50), 分别表示有n个亲属关系和m个问题, 然后接下来是n行的形式如ABC的字符串,表示A的父母亲分别是B和C,如果A的父母亲信息不全,则用-代替,例如A-C,再然后是m行形式如FA的字符串,表示询问F和A的关系。
输出描述:
如果询问的2个人是直系亲属,请按题目描述输出2者的关系,如果没有直系关系,请输出-。
具体含义和输出格式参见样例.
测试用例的输入:
10 10
EKL
LPY
YQR
RBG
GJD
DWT
TCA
AXZ
ZSN
NIF
DF
LX
SI
BG
GJ
WK
DJ
RW
TS
QI
测试用例的输出:
#include<iostream>
using namespace std;
int father[26], mother[26];
bool find(int old,int young,int& res) {//假设i为j的祖先
bool flag1 = false, flag2 = false;
if (old == young)return true;
if (father[young] != young) {
flag1 = find(old, father[young], res);
}
if (mother[young] != young) {
flag2 = find(old, mother[young], res);
}
if (flag1 || flag2) res++;
else return false;
}
int main() {
int n, m;
while (cin >> n >> m) {
for (int i = 0; i < 26; i++) {
father[i] = mother[i] = i;
}
for (int i = 0; i < n; i++) {
string relation;
cin >> relation;
char self = relation[0];
char fa = relation[1];
char mo = relation[2];
if (fa != '-') {
father[self - 'A'] = fa - 'A';
}
if (mo != '-') {
mother[self - 'A'] = mo - 'A';
}
}
for (int i = 0; i < m; i++) {
string q;
cin >> q;
int q0 = q[0] - 'A';
int q1 = q[1] - 'A';
int res = 0;
string ans = "";
bool flag1 = find(q0, q1, res);
if (flag1) {
if (res > 1) {
while (res > 2) {
ans += "great-";
//cout << "great-";
res--;
}
ans += "grandparent";
//cout << "grandparent" << endl;
cout << ans << endl;
}
else {
cout << "parent" << endl;
}
continue;
}
res = 0;
bool flag2 = find(q1, q0, res);
if (flag2) {
if (res > 1) {
while (res > 2) {
ans += "great-";
//cout << "great-";
res--;
}
ans += "grandchild";
cout << ans << endl;
//cout << "grandchild" << endl;
}
else {
cout << "child" << endl;
}
continue;
}
cout << "-" << endl;
}
}
}