显示代码纯文本
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
const int maxn=100000+100;
const int maxm=200000+100;
int n;
int m;
int q;
int a;
int b;
int w;
int kount1=1;
int kount2=1;
int head[maxn];
int head1[maxn];
int father[maxn];
int rank[maxn];
int u[maxm];
int v[maxm];
int vis[maxn];
int dis[maxn];
int lca[maxm];
struct T1
{
int to;
int next;
int w;
}A1[2*maxn];
inline void adde(int a,int b,int w)
{
A1[++kount1].next=head[a];
A1[kount1].to=b;
A1[kount1].w=w;
head[a]=kount1;
}
struct T2
{
int to;
int next;
int w;
}A2[2*maxm];
inline void addq(int a,int b,int w)
{
A2[++kount2].next=head1[a];
A2[kount2].to=b;
A2[kount2].w=w;
head1[a]=kount2;
}
inline int find(int x)
{
if(father[x]!=x)
{
father[x]=find(father[x]);
}
return father[x];
}
inline void unionn(int x,int y)
{
father[x]=y;
}
inline void tarjan(int x)
{
vis[x]=1;
for(int i=head[x];i;i=A1[i].next)
{
if(!vis[A1[i].to])
{
dis[A1[i].to]=dis[x]+A1[i].w;
tarjan(A1[i].to);
unionn(A1[i].to,x);
}
}
vis[x]=2;
for(int i=head1[x];i;i=A2[i].next)
{
if(vis[A2[i].to]==2)
{
lca[A2[i].w]=find(A2[i].to);
}
}
}
int main()
{
freopen("ThefallingofZLX.in","r",stdin);
freopen("ThefallingofZLX.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i)
{
father[i]=i;
}
for(int i=1;i<n;++i)
{
scanf("%d%d%d",&a,&b,&w);
adde(a,b,w);
adde(b,a,w);
}
scanf("%d",&q);
for(int i=1;i<=q;++i)
{
scanf("%d%d",&u[i],&v[i]);
addq(u[i],v[i],i);
addq(v[i],u[i],i);
}
tarjan(1);
for(int i=1;i<=q;++i)
{
cout<<dis[v[i]]+dis[u[i]]-dis[lca[i]]*2<<endl;
}
return 0;
}