#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<string.h>
using namespace std;
const int maxn = 50005;
int n, m, num,qnum, ans;
int head[maxn], qhead[maxn], fa[maxn], dis[maxn], f[maxn][20], a[maxn][3];
bool vis[maxn];
struct node {
int next, to, dist;
}e[maxn];
struct qnode
{
int next, to, k;
}q[maxn<<1];
void add(int from,int to,int dist)
{
e[++num].next = head[from];
e[num].to = to;
e[num].dist = dist;
head[from] = num;
}
void qadd(int from, int to, int k)
{
q[++qnum].next = qhead[from];
q[num].to = to;
q[num].k = k;
qhead[from] = qnum;
}
int find(int x)
{
if (x == fa[x])return fa[x];
return fa[x] = fa[fa[x]];
}
void merge(int x, int y)
{
int fx = find(x);
int fy = find(y);
fa[fx] = fy;
}
void tarjan(int x)
{
vis[x] = true;
for (int i = qhead[x]; i; i = q[i].next) {
int to = q[i].to;
int k = q[i].k;
if (vis[to])a[k][2] = find(to);
}
for (int i = head[x]; i; i = e[i].next) {
int to = e[i].to;
if (!vis[to]) {
dis[to] = dis[x] + e[i].dist;
tarjan(to);
merge(to, x);
}
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)fa[i] = i;
for (int i = 1; i < n; i++) {
int u, v, d;
cin >> u >> v >> d;
add(u, v, d);
add(v, u, d);
}
cin >> m;
for (int i = 1; i <= m; i++) {
cin >> a[i][0] >> a[i][1];
qadd(a[i][0], a[i][1], i);
qadd(a[i][1], a[i][0], i);
}
tarjan(0);
for (int i = 1; i <= m; i++) {
cout << dis[a[i][0]] + dis[a[i][1]] - 2 * dis[a[i][2]];
}
return 0;
}
LCA模板 Tarjan
最新推荐文章于 2020-07-22 18:49:21 发布