题解:P8855 [POI 2002] 商务旅行
Chengqijun2012 · · 题解
题解:P8855 [POI 2002] 商务旅行
题目大意:给你一棵有
解题思路:
先看数据范围,
我们先预处理 LCA,然后从路径中的第二个节点开始遍历。对于路径中的第
然后用树上差分求
这个式子是怎么的来的呢?请看下图:
我们要求节点
解题步骤到此结束,总体时间复杂度
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;
}
完结撒花!!!