How far away ?
题解:
最近公共祖先的裸题。
代码:
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 4e4+10;
//ver:节点编号 first:点编号第一次位置 dir:距离
int dp[20][maxn<<1], to;
int tot, ver[maxn<<1], head[maxn], first[maxn], dep[maxn<<1], dir[maxn], vis[maxn];
//边的属性,
struct edge{
int v, w, next;
}e[maxn<<1];
void init(){
tot = 0;
to = 0;
memset(head, -1, sizeof(head));
memset(vis, false, sizeof(vis));
}
void addEdge(int u, int v, int w){
e[to].v = v;
e[to].w = w;
e[to].next = head[u];
head[u] = to++;
}
void dfs(int u, int dis){
vis[u] = true;
ver[++tot] = u;
first[u] = tot;
dep[tot] = dis;
for(int i = head[u]; ~i; i = e[i].next){
if(!vis[e[i].v]){
int v = e[i].v;
int w = e[i].w;
dir[v] = dir[u] + w;
dfs(v, dis+1);
ver[++tot] = u;
dep[tot] = dis;
}
}
}
void RMQ(int N, int limits){
for(int i = 1; i <= N; ++i){
dp[0][i] = i;
}
for(int i = 1; i <= limits; ++i){
for(int j = 1; j <= N; ++j){
if(j+(1<<i)-1 <= N){
int a = dp[i-1][j];
int b = dp[i-1][j+(1<<i>>1)];
dp[i][j] = (dep[a]<dep[b] ? a:b);
}
}
}
}
int query(int l, int r){
int k = floor(log2(r-l+1));
int a = dp[k][l];
int b = dp[k][r-(1<<k)+1];
return dep[a]<dep[b] ? a:b;
}
int LCA(int u, int v){
int x = first[u];
int y = first[v];
if(x>y){
swap(x, y);
}
int res = query(x, y);
return ver[res];
}
int main(){
int t, n, q;
int u, v, w;
scanf("%d", &t);
while(t--){
init();
scanf("%d %d", &n, &q);
for(int i = 0; i < n-1; ++i){
//从 u 到 v 的权值 w
scanf("%d %d %d", &u, &v, &w);
addEdge(u, v, w);
addEdge(v, u, w);
}
dfs(1, 1);
dir[1] = 0;
RMQ(2*n-1, (log2(2*n-1)+1));
for(int i = 0; i < q; ++i){
int u, v, f;
scanf("%d %d", &u, &v);
f = LCA(u, v);
printf("%d\n", dir[u] + dir[v] - 2*dir[f]);
}
}
return 0;
}