游客 Signup | Login
中文 | En

3650 - 树的公共祖先

给定一棵二叉树和两个不同的节点,求出他们最近的公共祖先父节点。已知该二叉树有n个节点,标号1..n。(n<100)

Input

输入:
第一行两个整数x,y,表示需要计算的节点;
以下若干行,每行两个整数a和b,表示a的父节点是b。

Output

输出:
X与y的最近公共祖先root。

Examples

Input

9 7
2 1
3 2
4 2
5 3
8 5
9 5
6 4
7 4

Output

2

Solution C++

#include<cstdio>
const int N=100;
int x,y;
int f[N];
bool g[N];
int main()
{
	int a,b;
	scanf("%d%d",&x,&y);
	for(int i=1;i<N;i++)
		f[i]=i;
	while(scanf("%d%d",&a,&b)!=EOF)
		f[a]=b;
	g[y]=true;
	while(y!=f[y])
		y=f[y],g[y]=true;
	while(g[x]!=true)
		x=f[x];
	printf("%d\n",x);
	return 0;
}
Time Limit 1 second
Memory Limit 128 MB
Discuss Stats
上一题 下一题