多次查询树上两点之间的距离。
先预处理bfs,求出树根到各个点的距离和各个点的深度,同时更新f[maxn][20],f(x,k)表示x的2^k辈祖先
f(x,0)就是x的父节点。对于任意k,[1,logn], f[x,k]=f[f[x,k-1],k-1]。
求lca时,将x,y调整至同一深度,再逐步向上寻找。
#include <iostream>
#include <map>
#include <vector>
#include <cstring>
#include <cstdio>
#include <queue>
#include <algorithm>
#define LL long long
using namespace std;
const int maxn = 100005;
int n, m, t, cnt;
int f[maxn][20];
int head[maxn];
LL d[maxn], dis[maxn];
struct node
{
int u, v, w, nex;
}edge[maxn];
void addedge(int u, int v, int w)
{
edge[cnt].u = u;
edge[cnt].v = v;
edge[cnt].w = w;
edge[cnt].nex = head[u];
head[u] = cnt++;
}
void init()
{
memset(f, 0, sizeof(f));
for (int i = 0; i < maxn; i++)
{
head[i]=-1;
d[i] = 0;
}
cnt = 0;
}
void bfs()
{
queue<int>q;
q.push(1);
d[1] = 1;
while (!q.empty())
{
int h = q.front();
q.pop();
for (int i = head[h]; i != -1; i = edge[i].nex)
{
int v = edge[i].v;
int w = edge[i].w;
if (d[v]) continue;
d[v] = d[h] + 1;
dis[v] = dis[h] + w;
f[v][0] = h;
for (int j = 1; j <= t; j++)
f[v][j] = f[f[v][j - 1]][j - 1];
q.push(v);
}
}
}
int lca(int x, int y)
{
if (d[x] > d[y]) swap(x, y);
for (int i = t; i >= 0; i--)
if (d[f[y][i]] >= d[x])
y = f[y][i];
if (x == y)
return x;
for (int i = t; i >= 0; i--)
if (f[x][i] != f[y][i])
x = f[x][i], y = f[y][i];
return f[x][0];
}
int main()
{
int T;
ios::sync_with_stdio(false);
cin >> T;
int cnt = 1;
while (T--)
{
cin >> n >> m;
t = (int)(log(n) / log(2)) + 1;//树的可能最大深度
init();
for (int i = 0; i < n - 1; i++)
{
int a, b, c;
cin >> a >> b >> c;
addedge(a, b, c);
addedge(b, a, c);
}
bfs();
for (int i = 0; i < m; i++)
{
int x, y;
cin >> x >> y;
LL ans = dis[x] + dis[y] - 2 * dis[lca(x, y)];
cout << ans << endl;
}
//cout << endl;
}
return 0;
}