首页 > 代码库 > 【poj1986】 Distance Queries

【poj1986】 Distance Queries

http://poj.org/problem?id=1986 (题目链接)

题意

  给出一棵树,询问树上两点间距离

Solution

  lca。

代码

// poj1985#include<algorithm>#include<iostream>#include<cstdlib>#include<cstring>#include<cstdio>#include<cmath>#define LL long long#define MOD 100000000#define inf 2147483640#define Pi acos(-1.0)#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);using namespace std;const int maxn=400010;struct edge {int to,next,w;}e[maxn<<1];int n,m,cnt,head[maxn],deep[maxn],sum[maxn],bin[40],fa[maxn][40];void link(int u,int v,int w) {	e[++cnt].to=v;e[cnt].next=head[u];head[u]=cnt;e[cnt].w=w;	e[++cnt].to=u;e[cnt].next=head[v];head[v]=cnt;e[cnt].w=w;}void dfs(int x) {	for (int i=1;i<=30;i++) fa[x][i]=fa[fa[x][i-1]][i-1];	for (int i=head[x];i;i=e[i].next) if (e[i].to!=fa[x][0]) {			deep[e[i].to]=deep[x]+1;			sum[e[i].to]=sum[x]+e[i].w;			fa[e[i].to][0]=x;			dfs(e[i].to);		}}int lca(int x,int y) {	if (deep[x]<deep[y]) swap(x,y);	int t=deep[x]-deep[y];	for (int i=0;bin[i]<=t;i++) if (bin[i]&t) x=fa[x][i];	for (int i=30;i>=0;i--) if (fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i];	return x==y ? x : fa[x][0];}int main() {	bin[0]=1;for (int i=1;i<=30;i++) bin[i]=bin[i-1]<<1;	scanf("%d%d",&n,&m);	char ch;	for (int u,v,w,i=1;i<=m;i++) {		scanf("%d%d%d %c",&u,&v,&w,&ch);		if (u==v) continue;		link(u,v,w);	}	dfs(1);	int q;scanf("%d",&q);	while (q--) {		int x,y;		scanf("%d%d",&x,&y);		int f=lca(x,y);		printf("%d\n",sum[x]+sum[y]-2*sum[f]);	}	return 0;}

  

【poj1986】 Distance Queries