# Nearest Common Ancestors

140人阅读 评论(0)

In the figure, each node is labeled with an integer from {1, 2,...,16}. Node 8 is the root of the tree. Node x is an ancestor of node y if node x is in the path between the root and node y. For example, node 4 is an ancestor of node 16. Node 10 is also an ancestor of node 16. As a matter of fact, nodes 8, 4, 10, and 16 are the ancestors of node 16. Remember that a node is an ancestor of itself. Nodes 8, 4, 6, and 7 are the ancestors of node 7. A node x is called a common ancestor of two different nodes y and z if node x is an ancestor of node y and an ancestor of node z. Thus, nodes 8 and 4 are the common ancestors of nodes 16 and 7. A node x is called the nearest common ancestor of nodes y and z if x is a common ancestor of y and z and nearest to y and z among their common ancestors. Hence, the nearest common ancestor of nodes 16 and 7 is node 4. Node 4 is nearer to nodes 16 and 7 than node 8 is.

For other examples, the nearest common ancestor of nodes 2 and 3 is node 10, the nearest common ancestor of nodes 6 and 13 is node 8, and the nearest common ancestor of nodes 4 and 12 is node 4. In the last example, if y is an ancestor of z, then the nearest common ancestor of y and z is y.

Write a program that finds the nearest common ancestor of two distinct nodes in a tree.

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#include <functional>
#include <cmath>
#include <cctype>
#include <cfloat>
#include <climits>
#include <complex>
#include <deque>
#include <list>
#include <set>
#include <utility>
#define rt return
#define fr freopen("in.txt","r",stdin)
#define fw freopen("out.txt","w",stdout)
#define ll long long
#define ull unsigned long long
#define detie ios_base::sync_with_stdio(false);cin.tie(false);cout.tie(false)
#define pii pair<int,int>
#define lowbit(x) x&(-x)
using namespace std;
#define maxi 0x3f3f3f3f
#define MAX 100010

map<int, int> m;
vector<int> va, vb;
int main()
{
//fr;
detie;
int T;
cin >> T;
while (T--)
{
m.clear();
va.clear();
vb.clear();
int n, a, b;
cin >> n;
for (int i = 0; i < n - 1; i++)
{
cin >> a >> b;
m[b] = a;
}
cin >> a >> b;
while (m.count(a))
{
va.push_back(a);
a = m[a];
}
va.push_back(a);
while (m.count(b))
{
vb.push_back(b);
b = m[b];
}
vb.push_back(b);
bool flag = false;
int ans;
for (int i = 0; i < va.size() && !flag; i++)
{
for (int j = 0; j < vb.size() && !flag;j++)
{
if (va[i] == vb[j])
{
ans = va[i];
flag = true;
}
}
}
printf("%d\n", ans);
}
rt 0;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：3121次
• 积分：597
• 等级：
• 排名：千里之外
• 原创：59篇
• 转载：0篇
• 译文：0篇
• 评论：0条
友情链接
评论排行