题目>>http://codevs.cn/problem/2370/
变量名及其他参照:http://blog.youkuaiyun.com/qq_36519085/article/details/77187441
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int MAXN = 4e5 + 5;
int n,m,firs[MAXN],nex[MAXN],cnt = 0,num = 0,a,b,c;
struct zt
{
int f,t,v;
}road[MAXN];
struct zz
{
int num,deep,dis,sz;
zz *fa,*son,*top;
}tree[MAXN];
zz *fin[MAXN];
void build(int f,int t,int v)
{
road[++cnt] = (zt){f,t,v};
nex[cnt] = firs[f];
firs[f] = cnt;
}
void build_tree(zz *root,int x,int f,int v)
{
root->num = x;root->dis = v;fin[x] = root;
root->deep = root->fa->deep + 1;
root->sz = 1;
for(int i = firs[x];i != -1;i = nex[i])
{
int u = road[i].t;
if(u != f)
{
tree[++num].fa = root;
build_tree(&tree[num],u,x,v + road[i].v);
root->sz += fin[u]->sz;
if(!root->son||root->son->sz < fin[u]->sz) root->son = fin[u];
}
}
}
void dfs(zz *root,zz *j)
{
root->top = j;
if(!root->son) return;
if(root->son) dfs(root->son,j);
for(int i = firs[root->num];i != -1;i = nex[i])
{
int v = road[i].t;
if(v != root->son->num&&v != root->fa->num)
dfs(fin[v],fin[v]);
}
}
int lca(int a,int b)
{
while(fin[a]->top != fin[b]->top)
{
if(fin[a]->top->deep > fin[b]->top->deep)
a = fin[a]->top->fa->num;
else b = fin[b]->top->fa->num;
}
return fin[a]->deep > fin[b]->deep ? b : a;
}
int main()
{
scanf("%d",&n);
for(int i = 0;i <= n;i ++) firs[i] = -1;
for(int i = 1;i < n;i ++)
{
scanf("%d%d%d",&a,&b,&c);
build(a,b,c);
build(b,a,c);
}//以上为基本建图
tree[0].fa = &tree[0];//确立根节点的父亲
build_tree(tree,0,0,0);
dfs(tree,tree);
scanf("%d",&m);
for(int i = 1;i <= m;i ++)
{
scanf("%d%d",&a,&b);
cout<<(fin[a]->dis + fin[b]->dis - (fin[lca(a,b)]->dis << 1))<<'\n';
}
}