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;
}

你可能感兴趣的:(LCA)