當n和m爲0時結束輸入。
具體含義和輸出格式參見樣例.
二叉樹(數組實現) + 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;
}