How far away ?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 34457 Accepted Submission(s): 13982
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<k<=40000).The houses are labeled from 1 to n.
Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int N = 4e4 + 10;
int t, n, m, u, v, w, head[N], head2[N], tot, tot2, fa[N], dis[N];
bool vis[N];
struct node
{
int v, next, dis;
}edge[N << 1];
struct query
{
int lca, u, v, next;
}q[205 << 1];
void init()
{
tot = 0;
tot2 = 0;
memset(head, -1, sizeof(head));
memset(head2, -1, sizeof(head2));
memset(vis, 0, sizeof(vis));
memset(dis, 0, sizeof(dis));
}
void add(int u, int v, int w)
{
edge[tot].next = head[u];
edge[tot].v = v;
edge[tot].dis = w;
head[u] = tot++;
}
void add2(int u, int v)
{
q[tot2].next = head2[u];
q[tot2].u = u;
q[tot2].v = v;
head2[u] = tot2++;
}
int Find(int x)
{
if(fa[x] != x)
fa[x] = Find(fa[x]);
return fa[x];
}
void tarjin(int u)
{
fa[u] = u;
vis[u] = 1;
for(int i = head[u]; ~i; i = edge[i].next)
{
int v = edge[i].v, w = edge[i].dis;
if(!vis[v])
{
dis[v] = dis[u] + w;
tarjin(v);
fa[v] = u;
}
}
for(int i = head2[u]; ~i; i = q[i].next)
{
int v = q[i].v;
if(vis[v])
{
q[i].lca = q[i ^ 1].lca = Find(v);
}
}
}
int main()
{
scanf("%d", &t);
while(t--)
{
init();
scanf("%d%d", &n, &m);
for(int i = 1; i < n; ++i)
{
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
add(v, u, w);
}
for(int i = 1; i <= m; ++i)
{
scanf("%d%d", &u, &v);
add2(u, v);
add2(v, u);
}
tarjin(1);
for(int i = 0; i < m; ++i)
{
int u = q[2 * i].u;
int v = q[2 * i].v;
int w = q[2 * i].lca;
cout<<dis[u] + dis[v] - 2 * dis[w]<<'\n';
}
}
return 0;
}