too difficult

###### POJ 1330 Nearest Common Ancestors

#include <iostream>
#include <vector>
#include <cstdio>

using namespace std;

const int MAX=10005;
vector<int> G[MAX];
int depth[MAX];
int parent[MAX];
int root, n;
bool vis[MAX];

void dfs(int v, int p, int d)
{
parent[v] = p;
depth[v] = d;
for (int i=0;i<G[v].size(); i++)
{
if (G[v][i] != p)
dfs(G[v][i], v, d+1);
}
}

void init()
{
for(int i = 1; i <= n; i++)
if(!vis[i])
dfs(i, -1, 0);
}

int lca(int u, int v)
{
while (depth[u] > depth[v])
u = parent[u];
while (depth[v] > depth[u])
v = parent[v];
while (u != v)
{
u = parent[u];
v = parent[v];
}
return u;
}

int main()
{
std::ios::sync_with_stdio(false);
int T;
cin >> T;
while (T--)
{
cin >>  n;
for (int i = 1; i <= n; i++)
G[i].clear();
for (int i = 0; i < n-1; i++)
{
int t1,t2;
cin >> t1 >> t2;
G[t1].push_back(t2);
vis[t2] = true;
}
int f_u, f_v;
cin >> f_u >> f_v;
//root = 1;
//dfs(1, -1, 0);
init();
//cout << depth[f_v] << depth[f_u] << endl;
cout << lca(f_u,f_v) << endl;
}
return 0;
}

#### poj1330Nearest Common Ancestors以及讲解倍增法求lca

2015-04-16 20:03:13

#### POJ 1330 Nearest Common Ancestors 倍增法求LCA

2016-08-16 11:17:05

#### POJ 1330 Nearest Common Ancestors（求LCA的三种方法）

2012-08-08 04:29:37

#### poj - 1330 - Nearest Common Ancestors

2013-09-26 21:14:26

#### POJ.1330 Nearest Common Ancestors (LCA 倍增)

2017-08-11 19:16:57

#### POJ 1330 — Nearest Common Ancestors

2015-04-20 18:22:02

#### POJ 1330 Nearest Common Ancestors

2016-04-02 20:11:42

#### poj 1330 Nearest Common Ancestors

2013-11-11 15:45:07

#### 【poj 1330】 Nearest Common Ancestors

2016-10-18 12:42:09

#### POJ 1330：Nearest Common Ancestors

2015-06-15 14:48:21

## 不良信息举报

POJ 1330 Nearest Common Ancestors