原题:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3195
题意:有n个点,下面n-1行,输入两个点之间的距离。Q个询问,求联通三个点的最短长度;
裸LCA 直接贴代码了 ^_^
#include<stdio.h>
#include<queue>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 50005;
int n, Q, e;
int head[N];
int dep[N];
int dis[N];
int fa[N][20];
queue<int>q;
struct node
{
int to, val, nex;
}edge[N*2];
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)
{
dis[root] = 0;
fa[root][0] = root;
dep[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;
dis[v] = dis[u]+edge[i].val;
dep[v] = dep[u]+1;
fa[v][0] = u;
q.push(v);
}
}
}
int lca(int x, int y)
{
if(dep[x]<dep[y])
{
int t = y;
y = x;
x = t;
}
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 = 0;
while(scanf("%d", &n)!=EOF)
{
if(cas++)
printf("\n");
e = 0;
memset(head, -1, sizeof(head));
while(--n)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
add(b, a, c);
}
bfs(0);
scanf("%d", &Q);
while(Q--)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
int res = dis[a]+dis[b]+dis[c]-dis[lca(a, b)]-dis[lca(a, c)]-dis[lca(b, c)];
printf("%d\n", res);
}
}
return 0;
}