小A的最短路

小A的最短路

思路

树上问题求两个点的最短距离,显然能用 l c a lca 来进行 l o g n log_n 的查询,引入了两个无边权的点,所以我们的路劲就可以规划成三种 x > y x > u > v > y x > v > u > y x -> y, x -> u -> v -> y, x -> v -> u >- y ,只要在这三个当中取一个最小值就行了。接下来就是考虑求 l c a lca 了,有一种较为快速的求 l c a lca 的在线方法,那就是树链剖分,于是套上去(个人认为树剖求 l c a lca 较为好写),然后就可以开始最短路求解了。

代码


/*
  Author : lifehappy
*/
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include 
#define mp make_pair
#define pb push_back
#define endl '\n'

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair pii;

const double pi = acos(-1.0);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;

inline ll read() {
    ll f = 1, x = 0;
    char c = getchar();
    while(c  '9') {
        if(c == '-') f = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9') {
        x = (x << 1) + (x << 3) + (c ^ 48);
        c = getchar();
    }
    return f * x;
}

void print(ll x) {
    if(x < 10) {
        putchar(x + 48);
        return ;
    }
    print(x / 10);
    putchar(x % 10 + 48);
}

const int N = 3e5 + 10;

int sz[N], son[N], fa[N], dep[N], top[N], n, m;

int head[N], to[N << 1], nex[N << 1], cnt = 1;

void add(int x, int y) {
    to[cnt] = y;
    nex[cnt] = head[x];
    head[x] = cnt++;
}

void dfs1(int rt, int f) {
    fa[rt] = f, sz[rt] = 1;
    dep[rt] = dep[f] + 1;
    for(int i = head[rt]; i; i = nex[i]) {
        if(to[i] == f) continue;
        dfs1(to[i], rt);
        sz[rt] += sz[to[i]];
        if(!son[rt] || sz[to[i]] > sz[son[rt]]) son[rt] = to[i];
    }
}

void dfs2(int rt, int tp) {
    top[rt] = tp;
    if(!son[rt]) return ;
    dfs2(son[rt], tp);
    for(int i = head[rt]; i; i = nex[i]) {
        if(to[i] == fa[rt] || to[i] == son[rt]) continue;
        dfs2(to[i], to[i]);
    }
}

int lca(int x, int y) {
    while(top[x] != top[y]) {
        if(dep[top[x]] < dep[top[y]]) swap(x, y);
        x = fa[top[x]];
    }
    return dep[x] < dep[y] ? x : y;
}

int dis(int x, int y) {
    return dep[x] + dep[y] - 2 * dep[lca(x, y)];
}

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    //ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    n = read();
    for(int i = 1; i < n; i++) {
        int x = read(), y = read();
        add(x, y);
        add(y, x);
    }
    int u = read(), v = read();
    dfs1(1, 0);
    dfs2(1, 1);
    m = read();
    for(int i = 1; i <= m; i++) {
        int x = read(), y = read();
        printf("%d\n", min({dis(x, y), dis(x, u) + dis(v, y), dis(x, v) + dis(u, y)}));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45483201/article/details/107713975