**## 找出直系亲属**
题目来源 浙大计算机研究生复试上机考试-2009年
时间限制 1000 ms
空间限制 32768 kB
题目大意
如果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的关系。
当n和m为0时结束输入。
输出
如果询问的2个人是直系亲属,请按题目描述输出2者的关系,如果没有直系关系,请输出-。
具体含义和输出格式参见样例.
样例输入
3 2
ABC
CDE
EFG
FA
BE
0 0
样例输出
great-grandparent
题记:使用并查集是关键
AC的C++代码如下:
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
const int N = 1010;
int pre[N];
int unionsearch(int a, int b) //这里假定a是孩子,b是长辈
{
int count = 1;
while (b != -1)
{
if (pre[b] == a)
return count;
else
{
b = pre[b];
count++;
}
}
return -1;
}
int main()
{
int m, n, sum1, sum2;
string str;
string ge = "great-", pa = "parent", ch = "child", ga = "grand";
while (cin >> n >> m)
{
if (n == m && m == 0) //当m, n 都是0时停止输入
break;
memset(pre, -1, sizeof pre); //pre数组全部元素初始化为-1
while (n--)
{
cin >> str;
for (int i = 1; i < str.size(); i++)
if(isalpha(str[i]))
pre[str[i] - 'A'] = str[0] - 'A'; //记录亲自关系
}
while (m--)
{
cin >> str;
//由于不知道辈分关系,所以需要调用两次函数
sum1 = unionsearch(str[0] - 'A', str[1] - 'A');
sum2 = unionsearch(str[1] - 'A', str[0] - 'A');
if (sum1 == sum2 && sum1 == -1) cout << "-" << endl; //当两次调用结果全是-1,说明没有亲属关系
else if(sum1 != -1) //sum1不为-1,说明前者是孩子
{
if (sum1 == 1) cout << ch << endl;
else if (sum1 == 2) cout << ga << ch << endl;
else
{
for (int i = 2; i < sum1; i++)
cout << ge;
cout << ga << ch << endl;
}
}
else if (sum2 != -1) //sum2不为-1,说明后者是孩子
{
if (sum2 == 1) cout << pa << endl;
else if (sum2 == 2) cout << ga << pa << endl;
else
{
for (int i = 2; i < sum2; i++)
cout << ge;
cout << ga << pa << endl;
}
}
}
}
}