Problem Description
如果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-。
Input
输入包含多组测试用例,每组用例首先包含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时结束输入。
当n和m为0时结束输入。
Output
如果询问的2个人是直系亲属,请按题目描述输出2者的关系,如果没有直系关系,请输出-。
具体含义和输出格式参见样例.
具体含义和输出格式参见样例.
Sample Input
3 2 ABC CDE EFG FA BE 0 0
Sample Output
great-grandparent -
二叉树(数组实现) + dfs
#include <stdio.h>
#include <stdlib.h>#include <string.h>
typedef struct tagTNode
{
int f;
int m;
}TNode;
TNode table[26];
int dep, result, find;
void srh(int x, int y)
{
if (x < 26)
{
if (find)
{
return;
}
if (table[x].f == y || table[x].m == y)
{
dep++;
result = dep;
find = 1;
return;
}
if (table[x].f != '-')
{
dep++;
srh(table[x].f, y);
dep--;
}
if (table[x].m != '-')
{
dep++;
srh(table[x].m, y);
dep--;
}
}
}
void output(int gener, int postfixFthr)
{
if (gener == 1)
{
if (postfixFthr)
{
printf("parent\n");
}
else
{
printf("child\n");
}
}
else if (gener == 2)
{
if (postfixFthr)
{
printf("grandparent\n");
}
else
{
printf("grandchild\n");
}
}
else
{
int i;
for (i = 0; i < gener - 2; ++i)
{
printf("great-");
}
if (postfixFthr)
{
printf("grandparent\n");
}
else
{
printf("grandchild\n");
}
}
}
int main()
{
char ch, fa, mo;
char str[6];
int n, m, i;
int x, y;
while (scanf("%d%d", &n, &m) != EOF && n != 0 && m != 0)
{
for (i = 0; i < 26; ++i)
{
table[i].f = '-';
table[i].m = '-';
}
getchar();
for (i = 0; i < n; ++i)
{
gets(str);
if (str[1] != '-')
{
table[str[0] - 'A'].f = str[1] - 'A';
}
if (str[2] != '-')
{
table[str[0] - 'A'].m = str[2] - 'A';
}
}
for (i = 0; i < m; ++i)
{
gets(str);
x = str[0] - 'A';
y = str[1] - 'A';
dep = 0;
result = 0;
find = 0;
srh(x, y);
if (find)
{
output(result, 0);
}
else
{
dep = 0;
result = 0;
find = 0;
srh(y, x);
if (find)
{
output(result, 1);
}
else
{
printf("-\n");
}
}
}
}
return 0;
}