P8855 [POI2002] 商务旅行

· · 题解

luogu

思路

树上两点之间的最短路是 u \to \text{LCA}(u,v) \to v。因为边权为 1 所以这个值就是 dep_u + dep_v - 2\times dep_{\text{LCA}(u,v)} 然后随便写写就行了。

尤其注意减掉的东西是啥,要想明白,有些题不是这个公式。

Code

#include<bits/stdc++.h>

using namespace std;

#define endl '\n'

#define TRACE 1
#define tcout TRACE && cout

#define IN(o) insert(o)

#define fi first
#define se second

#define int long long

#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);

const int INF = 0x3f3f3f3f3f3f3f3f;

const int P = 998244353;

const int N = 1e6 + 10;

int n, m;

vector<int> G[N]; 

int dep[N], f[N][21];

void dfs(int u, int fa)
{
    f[u][0] = fa;
    dep[u] = dep[fa] + 1;
    for(auto v : G[u])
    {
        if(v == fa) continue;
        dfs(v, u);
    }
}

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

signed main()
{
    cin >> n;
    for(int i=1; i<n; i++)
    {
        int u, v;
        cin >> u >> v;
        G[u].push_back(v), G[v].push_back(u);
    }
    dfs(1, 0);
    for(int j=1; j<=20; j++)
    {
        for(int i=1; i<=n; i++)
        {
            f[i][j] = f[f[i][j-1]][j-1];
        }
    }
    cin >> m;
    int last = 0, res = 0;
    for(int i=1; i<=m; i++)
    {
        int x;
        cin >> x;
        if(i == 1)
        {
            last = x;
            continue;
        }
        res += dep[x] + dep[last] - 2 * dep[lca(x, last)];
        last = x;
    }
    cout << res;
    return 0;
}