原题:http://acm.hdu.edu.cn/showproblem.php?pid=2586
题意:n个点,m个询问,下面n-1行给出两点间距离;
问两点间的最短距离;
#include<stdio.h>
#include<queue>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
queue<int>q;
const int N = 40005;
int dep[N], fa[N][20];
int head[N], dis[N];
int e;
struct node
{
int to, nex, val;
}edge[N<<1];
void add(int u, int v, int w)
{
edge[e].to = v;
edge[e].val = w;
edge[e].nex = head[u];
head[u] = e++;
}
void bfs(int root)
{
fa[root][0] = root;
dep[root] = 0;
dis[root] = 0;
q.push(root);
while(!q.empty())
{
int u = q.front();
q.pop();
for(int i = 1;i<20;i++)
fa[u][i] = fa[fa[u][i-1]][i-1];
for(int i = head[u];i!=-1;i = edge[i].nex)
{
int v = edge[i].to;
if(v == fa[u][0])
continue;
dep[v] = dep[u]+1;
dis[v] = dis[u]+edge[i].val;
fa[v][0] = u;
q.push(v);
}
}
}
int lca(int x, int y)
{
if(dep[x]<dep[y])
swap(x, y);
for(int i = 0;i<20;i++)
{
if((dep[x]-dep[y])&(1<<i))
x = fa[x][i];
}
if(x == y)
return x;
for(int i = 19;i>=0;i--)
{
if(fa[x][i]!=fa[y][i])
{
x = fa[x][i];
y = fa[y][i];
}
}
return fa[x][0];
}
int main()
{
int cas;
scanf("%d", &cas);
while(cas--)
{
memset(head, -1, sizeof(head));
int n, m;
scanf("%d%d", &n, &m);
while(--n)
{
int a, b, w;
scanf("%d%d%d", &a, &b, &w);
add(a, b, w);
add(b, a, w);
}
bfs(1);
while(m--)
{
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", dis[a]+dis[b]-2*dis[lca(a, b)]);
}
}
return 0;
}