题目描述:
题目背景: SOURCE:NOIP2015-SHY
给出一棵带有边权的树,问两点之间的距离。
输入格式:
第一行两个整数 n 和 m ,分别表示点数和询问数。
接下来 n-1 行,每行三个整数 x,y,z,表示 x 与 y 通过一条权为 z 的边连接。
接下来 m 行,每行两个整数 x,y,代表一组询问。
输出格式:
输出 m 行,每行一个整数,对应一组询问的答案。
样例输入:
3 3
1 2 1
1 3 2
1 2
1 3
2 3
样例输出:
1
2
3
数据范围:
对 30% 的输入数据 :1≤n,m≤1000
对 100% 的输入数据 :1≤n,m≤100000;1≤z≤10000
题目分析:
LCA模板题。LCA有多种解决方法,下附代码用的是倍增思想。
附代码:
#include<iostream>
#include<cstring>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<ctime>
#include<queue>
#include<iomanip>
#include<cctype>
#include<cmath>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
const int maxn=1e6+5;
int n,m,tot,dis[maxn],dep[maxn],first[maxn],nxt[maxn];
int to[maxn],w[maxn],fa[maxn][25],x,y,z;
int readint()
{
int i=0,f=1;char ch;
for(ch=getchar();(ch<'0'||ch>'9')&&ch!='-';ch=getchar());
if(ch=='-')
{
ch=getchar();
f=-1;
}
for(;ch>='0'&&ch<='9';ch=getchar())
i=(i<<3)+(i<<1)+ch-'0';
return i*f;
}
void create(int x,int y,int z)
{
tot++;
nxt[tot]=first[x];
first[x]=tot;
to[tot]=y;
w[tot]=z;
}
void dfs(int u,int f)
{
fa[u][0]=f;
for(int i=1;i<=20;i++)
fa[u][i]=fa[fa[u][i-1]][i-1];
for(int e=first[u];e;e=nxt[e])
{
int v=to[e];
if(v!=f)
{
dis[v]=dis[u]+w[e];
dep[v]=dep[u]+1;
dfs(v,u);
}
}
}
int lca(int x,int y)
{
if(dep[x]<dep[y])
swap(x,y);
int d=dep[x]-dep[y];
for(int i=20;i>=0;i--)
if((1<<i)&d)
x=fa[x][i];
if(x==y) return x;
for(int i=20;i>=0;i--)
if(fa[x][i]!=fa[y][i])
x=fa[x][i],y=fa[y][i];
return fa[x][0];
}
int main()
{
//freopen("lx.in","r",stdin);
n=readint();m=readint();
for(int i=1;i<n;i++)
{
x=readint();y=readint();z=readint();
create(x,y,z);
create(y,x,z);
}
dis[1]=dep[1]=0;
dfs(1,0);
while(m--)
{
x=readint();y=readint();
printf("%d\n",dis[x]+dis[y]-2*dis[lca(x,y)]);
}
return 0;
}