九度OJ 1035:找出直系亲属 (二叉树、递归)

时间:2023-03-09 15:29:03
九度OJ 1035:找出直系亲属 (二叉树、递归)

时间限制:1 秒

内存限制:32 兆

特殊判题:否

提交:2380

解决:934

题目描述:
    如果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
-
来源:
2009年浙江大学计算机及软件工程研究生机试真题

思路:

因为本题的数据特点,将大写字母映射到数字,再利用数组建立二叉树比较方便。然后递归查找即可。

代码:

#include <stdio.h>

#define N 26

int a[N+1][2];

void init()
{
for (int i=0; i<=N; i++)
a[i][0] = a[i][1] = N;
} int c2i(char c)
{
return c-'A';
} int search(int x, int y, int step)
{
int k;
//printf("x=%d, y=%d, step=%d\n", x, y, step);
if (x == y)
return step;
if (a[x][0] == N && a[x][1] == N)
return -1;
if (a[x][0] != N)
{
k = search(a[x][0], y, step+1);
if (k >= 0)
return k;
}
if (a[x][1] != N)
{
k = search(a[x][1], y, step+1);
if (k >= 0)
return k;
}
return -1;
} void print(int step)
{
if (step > 0)
{
while (step > 2)
{
printf("great-");
step --;
}
if (step == 2)
printf("grand");
printf("child\n");
}
if (step < 0)
{
step = -step;
while (step > 2)
{
printf("great-");
step --;
}
if (step == 2)
printf("grand");
printf("parent\n");
}
} int main(void)
{
int n, m, i, x, y;
char s[10]; while (scanf("%d%d", &n, &m) != EOF)
{
if (n == 0 && m == 0)
break; init();
for (i=0; i<n; i++)
{
scanf("%s", s);
x = c2i(s[0]);
if (s[1] != '-')
a[x][0] = c2i(s[1]);
a[x][1] = c2i(s[2]);
} for (i=0; i<m; i++)
{
scanf("%s", s);
x = c2i(s[0]);
y = c2i(s[1]);
int step;
step = search(x, y, 0);
//printf("step = %d\n", step);
if (step > 0)
{
print(step);
continue;
}
step = search(y, x, 0);
//printf("step = %d\n", step);
if (step > 0)
{
print(-step);
continue;
}
printf("-\n");
}
} return 0;
}
/**************************************************************
Problem: 1035
User: liangrx06
Language: C
Result: Accepted
Time:0 ms
Memory:912 kb
****************************************************************/