[BZOJ2953][[Poi2002]商务旅行][LCA+水题]
就是求树上两点之间的距离。。
代码:
#include <bits/stdc++.h>
using namespace std;
const int Maxn = 50010;
inline char get(void) {
static char buf[1000000], *p1 = buf, *p2 = buf;
if (p1 == p2) {
p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin);
if (p1 == p2) return EOF;
}
return *p1++;
}
inline void read(int &x) {
x = 0; static char c; bool minus = false;
for (; !(c >= '0' && c <= '9'); c = get()) if (c == '-') minus = true;
for (; c >= '0' && c <= '9'; x = x * 10 + c - '0', c = get()); if (minus) x = -x;
}
int n, m, ans;
int head[Maxn], sub;
struct Edge {
int to, nxt;
Edge (void) {}
Edge (const int &to, const int &nxt) : to(to), nxt(nxt) {}
} edge[Maxn << 1];
inline void add(int a, int b) {
edge[++sub] = Edge(b, head[a]), head[a] = sub;
}
int dep[Maxn], ff[Maxn][25];
inline void dfs1(int u, int fa) {
ff[u][0] = fa;
for (int i = 1; i <= 20; i++) {
ff[u][i] = ff[ff[u][i - 1]][i - 1];
}
for (int i = head[u], v; i; i = edge[i].nxt) {
v = edge[i].to;
if (v == fa) continue;
dep[v] = dep[u] + 1;
dfs1(v, u);
}
}
inline int lca(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
int tmp = dep[x] - dep[y];
for (int k = 0, j = 1; j <= tmp; j <<= 1, k++)
if (tmp & j) x = ff[x][k];
while (x != y) {
int j = 0;
while (ff[x][j] != ff[y][j]) j++;
if (j) j--;
x = ff[x][j], y = ff[y][j];
}
return x;
}
inline int dist(int x, int y) {
return dep[x] + dep[y] - (dep[lca(x, y)] << 1);
}
int main(void) {
//freopen("in.txt", "r", stdin);
read(n);
int u, v;
for (int i = 1; i < n; i++) {
read(u), read(v);
add(u, v), add(v, u);
}
dfs1(1, 0);
read(m);
u = 1;
long long ans = 0;
while (m--) {
read(v); ans += dist(u, v);
u = v;
}
printf("%lld\n", ans);
return 0;
}
完。
By g1n0st