fastle
垆边人似月 皓腕凝霜雪
  • 这个题貌似是过的最少的?
  • smeow一眼给出了一个单log的算法orz
  • 首先求出x和y的lca, x和c的lca,y和c的lca, 然后分类讨论以下就行了
  • 实际上只有三种情况
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<iostream>
#define ll long long
#define M 100010
#define mmp make_pair
using namespace std;
int read() {
    int nm = 0, f = 1;
    char c = getchar();
    for(; !isdigit(c); c = getchar()) if(c == '-') f = -1;
    for(; isdigit(c); c = getchar()) nm = nm * 10 + c - '0';
    return nm * f;
}
int fa[M], top[M], son[M], sz[M], n, q, deep[M];
vector<int> to[M];
 
void dfs(int now, int f) {
    fa[now] = f;
    sz[now] = 1;
    deep[now] = deep[f] + 1;
    for(int i = 0; i < to[now].size(); i++) {
        int vj = to[now][i];
        if(vj == f) continue;
        dfs(vj, now);
        if(sz[son[now]] < sz[vj]) son[now] = vj;
        sz[now] += sz[vj];
    }
}
 
void dfs(int now) {
    if(son[now]) {
        top[son[now]] = top[now];
        dfs(son[now]);
    }
    for(int i = 0; i < to[now].size(); i++) {
        int vj = to[now][i];
        if(vj == fa[now] || vj == son[now]) continue;
        top[vj] = vj;
        dfs(vj);
    }
}
int lca(int a, int b) {
    for(; top[a] != top[b]; a = fa[top[a]]) {
        if(deep[top[a]] < deep[top[b]]) swap(a, b);
    }
    if(deep[a] > deep[b]) swap(a, b);
    return a;
}
int main() {
    n = read();
    for(int i = 1; i < n; i++) {
        int vi = read(), vj = read();
        to[vi].push_back(vj), to[vj].push_back(vi);
    }
    dfs(1, 0);
    top[1] = 1;
    dfs(1);
    q = read();
    while(q--) {
        int x = read(), y = read(), c = read();
        int l1 = lca(x, y), l2 = lca(x, c), l3 = lca(y, c), ans;
        if(l2 == l1) ans = l3;
        else if(l3 == l1) ans = l2;
        else ans = l1;
 
        cout << ans << "\n";
    }
    return 0;
}
posted on 2019-04-14 19:04  fastle  阅读(113)  评论(0编辑  收藏  举报