题解:P8855 [POI 2002] 商务旅行

· · 题解

题解:P8855 [POI 2002] 商务旅行

题目大意:给你一棵有 n 个节点,n-1 条边的树,再给你 m 个节点,求在这棵树上按顺序走完这些节点所需要的最短路径(每条边长固定为 1)。

解题思路:

先看数据范围,n \le 30000,O(n^{2}) 暴力显然不可行,考虑 LCA+树上差分。

我们先预处理 LCA,然后从路径中的第二个节点开始遍历。对于路径中的第 i 个节点,我们令 u=trip_{i-1},v=trip_{i},然后找出 u 和 v 的 LCA 并用一个变量 lca 存下来。

然后用树上差分求 u \to v 的路径长度。我们要提前在预处理的时候用一个数组记录每个节点到根节点的距离,而这道题每条边的长度都为 1,所以下面就直接用 dep 深度数组来代替。我们令 dist(u,v) 为 u \to v 的路径长度,于是得出:

dist(u, v)=dep_{u}+dep_{v}-dep_{lca} \times 2

这个式子是怎么的来的呢?请看下图:

我们要求节点 4 到节点 6 的路径 4 \to 2 \to 5 \to 6,且时间复杂度为 O(1)。那么根据上面的式子,先求出节点 4 和节点 6 的 LCA 为节点 2,然后把节点 4 和节点 6 到根节点的路径长度加起来,也就是 1 \to 2 \to 4 加上 1 \to 2 \to 5 \to 6,此时我们可以发现这里多加了两条 1 \to 2,于是我们减去两倍的 1 \to 2,就可以求出 4 \to 2 \to 5 \to 6 这条路径长度等于 3。

解题步骤到此结束,总体时间复杂度 O(n+m\log n)。

AC Code:

#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <climits>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <bitset>
#include <cstdio>
#define ll long long
#define P pair<int, int>
#define MP make_pair
#define PU push_back
#define li(x) x << 1
#define ri(x) (x << 1) | 1
#define LLF LLONG_MAX >> 2
#define INF INT_MAX >> 1
using namespace std;
const int N = 30000 + 5;
int n, m, tot, head[N], trip[N], dep[N], fa[N][25], ans;

struct Edge{
    int u, v, w, nex;
}e[N << 1];

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

inline void write(ll x){
    if(x < 0) putchar('-'), x = -x;
    if(x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

inline void add(int u, int v){
    e[++tot] = {u, v, 1, head[u]};
    head[u] = tot;
}

void DFS(int u, int fr){
    dep[u] = dep[fr] + 1;
    fa[u][0] = fr;
    for(int i = 1; i <= 20; i++) fa[u][i] = fa[fa[u][i - 1]][i - 1];
    for(int i = head[u]; i; i = e[i].nex){
        int v = e[i].v;
        if(v != fr) DFS(v, u);
    }
}

inline int LCA(int x, int y){
    if(dep[x] < dep[y]) swap(x, y);
    for(int i = 20; i >= 0; i--) if(dep[fa[x][i]] >= dep[y]) x = fa[x][i];
    if(x == y) return x;
    for(int i = 20; i >= 0; i--) if(fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i];
    return fa[x][0];
}

int main(){
//  freopen("water.in.txt", "r", stdin);
//  freopen("water.out.txt", "w", stdout);

//  ios::sync_with_stdio(false);
//  cin.tie(0), cout.tie(0);

    n = read();
    for(int i = 1, u, v; i < n; i++){
        u = read(), v = read();
        add(u, v);
        add(v, u);
    }
    DFS(1, 0);
    m = read();
    for(int i = 1; i <= m; i++) trip[i] = read();
    for(int i = 2; i <= m; i++){
        int u = trip[i - 1], v = trip[i];
        int lca = LCA(u, v);
        ans += dep[u] + dep[v] - (dep[lca] << 1);      //<<1相当于*2
    }
    write(ans), putchar('\n');
    return 0;
}

完结撒花!!!