链接
题目描述
给出n个点的一棵树,多次询问两点之间的最短距离。
样例输入
3 2
1 2 10
3 1 15
1 2
3 2
样例输出
10
25
思路
就LCA模板呗
代码
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int to, next, val;
}g[40005];
int n, m, t;
int h[40005];
int fa[40005][16], dep[40005], dis[40005];
void add(int x, int y, int k)
{
g[++t] = (node){y, h[x], k}; h[x] = t;
g[++t] = (node){x, h[y], k}; h[y] = t;
}
void dfs(int x, int fath)
{
fa[x][0] = fath; dep[x] = dep[fath] + 1;
for(int i = h[x]; i; i = g[i].next)
{
int to = g[i].to;
if(to == fath) continue;
dis[to] = dis[x] + g[i].val;
dfs(to, x);
}
return;
}
void ask(int x, int y, int lca)
{
printf("%d\n", dis[x] + dis[y] - 2 * dis[lca]);
return;
}
int LCA(int x, int y)
{
if(dep[x] < dep[y]) swap(x, y);
for(int i = 15; i >= 0; --i)
if(dep[fa[x][i]] >= dep[y])
x = fa[x][i];
if(x == y) return x;
for(int i = 15; i >= 0; --i)
if(fa[x][i] != fa[y][i])
{
x = fa[x][i];
y = fa[y][i];
}
return fa[x][0];
}
int main()
{
dep[0] = -1;
scanf("%d%d", &n, &m);
for(int i = 1; i < n; ++i)
{
int x, y, k;
scanf("%d%d%d", &x, &y, &k);
add(x, y, k);
}
dfs(1, 0);
for(int j = 1; j < 16; ++j)
for(int i = 1; i <= n; ++i)
fa[i][j] = fa[fa[i][j - 1]][j - 1];
for(int i = 1; i <= m; ++i)
{
int x, y;
scanf("%d%d", &x, &y);
int faa = LCA(x, y);
ask(x, y, faa);
}
return 0;
}