代码比较好理解,见注释
#include <stdio.h>
#include <string.h>
int parent[201];
int flag[201];
/* 找到father节点往上的所有祖先节点,并在flag[]数组中标记该节点已访问 */
void find_root(int father)
{
flag[father] = 1;
if (parent[father] == -1)
return ;
find_root(parent[father]);
}
/* 从father节点开始往上查找,遇到第一个flag[]被标记的节点,就是最近公共祖先 */
int find_common_ancient(int father)
{
if (1 == flag[father])
return father;
return find_common_ancient(parent[father]);
}
int main(int argc, char *argv[])
{
int T, N, M, father, child, a, b, I, J;
scanf("%d", &T);
for (J=0 ; J<T ; J++)
{
memset(parent, -1, sizeof(int) * 201);
scanf("%d", &N);
for (I=0 ; I<N-1 ; I++)
{
scanf("%d %d", &father, &child);
parent[child] = father;
}
printf("Case #%d:", J + 1);
scanf("%d", &M);
for (I=0 ; I<M ; I++)
{
scanf("%d %d", &a, &b);
memset(flag, 0, sizeof(int) * 201);
find_root(a);
printf("%d
", find_common_ancient(b));
}
}
}
|