ZOJ 3195 — Design the city

原题: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值