Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10292 Accepted Submission(s): 3727
Problem Description
There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this “How far is it if I want to go from house A to house B”? Usually it hard to answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path(“simple” means you can’t visit a place twice) between every two houses. Yout task is to answer all these curious people.
Input
First line is a single integer T(T<=10), indicating the number of test cases.
For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road connecting house i and house j,with length k(0
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<iostream>
using namespace std;
#define N 40005
struct Tarjan{
struct qEdge{int fr,to,lca;};
struct Edge{int fr,to,dis;};
vector<Edge> edge;vector<qEdge> qedge;
vector<int> qs[N];vector<int> g[N];
int p[N];long long d[N],ans[N];bool b[N];int n,m;
void Add_qEdge(int fr,int to){
qedge.push_back((qEdge){fr,to,0});
int ll=qedge.size();
qs[fr].push_back(ll-1);
qs[to].push_back(ll-1);
}
void Add_Edge(int fr,int to,int d){
edge.push_back((Edge){fr,to,d});edge.push_back((Edge){to,fr,d});
m=edge.size();
g[fr].push_back(m-2);g[to].push_back(m-1);
}
long long abs(long long x){return x>=0?x:-x;}
void dfs(int u,int f,long long w){
d[u]=w;
for(int i=0;i<g[u].size();i++){
Edge &e=edge[g[u][i]];
if(e.to==f) continue;
dfs(e.to,u,w+e.dis);
}
}
int Find(int x){return p[x]==x?x:p[x]=Find(p[x]);}
void Tarjan_Lca(int u){
p[u]=u;b[u]=true;
for(int i=0;i<g[u].size();i++){
Edge &e=edge[g[u][i]];
if(!b[e.to]){
Tarjan_Lca(e.to);
p[e.to]=u;
}
}
for(int i=0;i<qs[u].size();i++){
qEdge &e=qedge[qs[u][i]];
if(u==e.fr&&b[e.to]){
e.lca=Find(e.to);
ans[qs[u][i]]=abs(d[u]+d[e.to]-2*d[e.lca]);
}
if(u==e.to&&b[e.fr]){
e.lca=Find(e.fr);
ans[qs[u][i]]=abs(d[u]+d[e.fr]-2*d[e.lca]);
}
}
}
void init(){
edge.clear();qedge.clear();
for(int i=0;i<=n;i++) g[i].clear(),qs[i].clear();
memset(d,0,sizeof(d));memset(ans,0,sizeof(ans));
};
void Solve(int n,int m){
this->n=n;this->m=m;int x,y,z;
for(int i=0;i<=n;i++) p[i]=i;
for(int i=1;i<n;i++){
scanf("%d%d%d",&x,&y,&z);
Add_Edge(x,y,z);
}
for(int i=0;i<m;i++){
scanf("%d%d",&x,&y);
Add_qEdge(x,y);
}
dfs(1,0,0);Tarjan_Lca(1);
for(int i=0;i<m;i++) printf("%lld\n",ans[i]);
init();
}
}s;
int main(){
int t,n,m;scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
s.Solve(n,m);
}
return 0;
}