显示代码纯文本
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
int n,q,mp[1010][1010]={0},a[1010][1010]={0},num[1010];
int h,t,jd[1010];
void bfs(int st)
{
bool pd[1010]={0};
h=0;
t=1;
jd[1]=st;
pd[st]=1;
while(h!=t)
{
++h;
for(int i=1;i<=num[jd[h]];++i)
{
if(pd[mp[jd[h]][i]]==0)
{
++t;
jd[t]=mp[jd[h]][i];
pd[jd[t]]=1;
a[st][jd[t]]=a[st][jd[h]]+a[jd[h]][jd[t]];
}
}
}
}
int main()
{
freopen("pwalk.in","r",stdin);
freopen("pwalk.out","w",stdout);
scanf("%d%d",&n,&q);
for(int i=1;i<n;++i)
{
int t1,t2,t3;
scanf("%d%d%d",&t1,&t2,&t3);
a[t1][t2]=a[t2][t1]=t3;
mp[t1][++num[t1]]=t2;
mp[t2][++num[t2]]=t1;
}
/*
for(int i=1;i<=n;++i)
{
for(int j=1;j<=n;++j)
{
cout<<a[i][j]<<' ';
}
cout<<endl;
}
cout<<endl;
*/
for(int i=1;i<=n;++i)
{
bfs(i);
}
/*
for(int i=1;i<=n;++i)
{
for(int j=1;j<=n;++j)
{
cout<<a[i][j]<<' ';
}
cout<<endl;
}
cout<<endl;
*/
for(int i=1;i<=q;++i)
{
int t1,t2;
scanf("%d%d",&t1,&t2);
printf("%d\n",a[t1][t2]);
}
return 0;
}