#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int maxm = 16;
const int maxn = 1 << 16;
struct LCA {
    vector <int> e[maxn];
    int d[maxn],p[maxn][maxm];
    void dfs_(int v,int f) {
        p[v][0] = f;
        for(int i=1;i<maxm;++i) {
            p[v][i]=p[p[v][i-1]][i-1];
        }
        for(int i=0;i<(int)e[v].size();++i) {
            int w = e[v][i];
            if(w != f) {
                d[w] = d[v] + 1;
                dfs_(w , v);
            }
        }
    }
    int up_(int v,int m) {
        for(int i=0;i<maxm;++i) {
            if(m & (1<<i)) {
                v = p[v][i];
            }
        }
        return v;
    }
    int lca(int a,int b) {
        if(d[a] > d[b]) {
            swap(a , b);
        }
        b = up_(b , d[b]-d[a]);
        if(a == b) {
            return a;
        } else {
            for(int i=maxm-1;i>=0;--i) {
                if(p[a][i] != p[b][i]) {
                    a = p[a][i];
                    b = p[b][i];
                }
            }
            return p[a][0];
        }
    }
    void init(int n) {
        for(int i=0;i<n;++i) {
            e[i].clear();
        }
    }
    void add(int a,int b) {
        e[a].push_back(b);
        e[b].push_back(a);
    }
    void build() {
        d[0] = 0;
        dfs_(0 , 0);
    }
} lca;

int main() {
    int n , m;
    while(~scanf("%d",&n)) {
        lca.init(n);
        for(int i=1;i<n;i++) {
            int u , v;
            scanf("%d%d",&u,&v);
            lca.add(u , v);
        }
        lca.build();
        scanf("%d" , &m);
        while(m--) {
            int u , v;
            scanf("%d%d",&u,&v);
            int ans = lca.lca(u,v);
            printf("%d\n" , ans);
        }
    }
    return 0;
}

 

 posted on 2013-08-18 12:33  tobec  阅读(367)  评论(0编辑  收藏  举报