题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2586
#include<iostream>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#include<string.h>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
#include<fstream>
#include<cstdlib>
#include<ctime>
#include<list>
#include<climits>
#include<bitset>
using namespace std;
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fopen freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);
#define scd(a) scanf("%d",&a)
#define scf(a) scanf("%lf",&a)
#define scl(a) scanf("%lld",&a)
#define sci(a) scanf("%I64d",&a)
#define scs(a) scanf("%s",a)
#define left asfdasdasdfasdfsdfasfsdfasfdas1
#define tan asfdasdasdfasdfasfdfasfsdfasfdas
typedef long long ll;
typedef unsigned int un;
const int desll[][]={{,},{,-},{,},{-,}};
const ll mod=1e9+;
const int maxn=4e4+;
const int maxm=3e8+;
const double eps=1e-;
int m,n; struct node
{
int b,nex,c;
}no[maxn*];
int head[maxn],sz=;
int add(int a,int b,int c){
no[sz].b=b;
no[sz].c=c;
no[sz].nex=head[a];
head[a]=sz++;
}
int father[maxn],tan[maxn*][],dep[maxn];
int ar[maxn*],le,in[maxn];
ll dis[maxn];
void dfs1(int u,int pre){
for(int i=head[u];i!=-;i=no[i].nex){
int v=no[i].b;
if(v==pre)continue;
dis[v]=dis[u]+no[i].c;
father[v]=u;
dep[v]=dep[u]+;
ar[le++]=u;
dfs1(v,u);
}
in[u]=le;
ar[le++]=u;
}
void init()
{
memset(tan,,sizeof(tan));
for(int i=;i<le;i++){
tan[i][]=ar[i];
}
for(int j=;j<;j++){
for(int i=le-;i>=;i--){
if(i+(<<j)->=le)continue;
int x=tan[i][j-],y=tan[i+(<<(j-))][j-];
if(dep[x]<dep[y])tan[i][j]=x;
else tan[i][j]=y;
//cout<<i<<" "<<j<<" "<<tan[i][j]<<endl;
}
}
}
int sameFather(int a,int b)
{
a=in[a];
b=in[b];
if(a>b)swap(a,b);
int res=floor(log(b-a+)/log());
int x=tan[a][res],y=tan[b-(<<res)+][res];
if(dep[x]<dep[y])return x;
else return y;
} int main()
{
int t;scd(t);
while(t--){
scd(n);scd(m);
memset(head,-,sizeof(head));sz=;
for(int i=;i<n;i++){
int a,b,c;
scd(a);scd(b);scd(c);
add(a,b,c);
add(b,a,c);
}
memset(dis,,sizeof(dis));
memset(dep,,sizeof(dep));
dep[]=;
dfs1(,);
father[]=;
init();
for(int i=;i<m;i++){
int a,b;
scd(a);scd(b);
int x=sameFather(a,b);
printf("%d\n",dis[a]+dis[b]-*dis[x]);
}
}
return ;
}