POJ-2631 ~~Roads in the North

Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are build such that there is only one route from a village to a village that does not pass through some other village twice. 
Given is an area in the far North comprising a number of villages and roads among them such that any village can be reached by road from any other village. Your job is to find the road distance between the two most remote villages in the area. 

The area has up to 10,000 villages connected by road segments. The villages are numbered from 1.


Input

Input to the problem is a sequence of lines, each containing three positive integers: the number of a village, the number of a different village, and the length of the road segment connecting the villages in kilometers. All road segments are two-way.


Output

You are to output a single integer: the road distance between the two most remote villages in the area.


Sample Input

5 1 6
1 4 5
6 3 9
2 6 8
6 1 7

Sample Output

22

题目大意:给你一棵树,求树上最远的两点距离为多少。(题目描述比较奇葩,你可以认为点数等于边数+1,所有运算不会超过2^31-1)

思路:从任意一点开始,找到离这个点最远的点x。再从x开始做单源最短路,离x最远的点和x就是这棵树的最远点对。(当然基于树的分治也是可以做的)

证明(参考DISCUSS):

设最长链是MN->已知[1]
设由A开始DFS得到最长路为AB->已知[2]
结论[1] MN与AB有公共点.否则MN<AM+AN<=AM+AB=BM 与已知[1]矛盾
结论[2] B是最长链的一个端点.否则由结论[1] 设K是AB上距B最近且在MN上的点 则MN=MK+KN=MK+AN-AK<=MK+AB-AK=MK+BK=BM 当取等号时MB与MN等长 符合结论[2] 否则与已知[1]矛盾  [这里假定了A不在NK上.若A在NK上 只须将上面式子中MN交换位置即可 不影响结论]
结论[3] 从B开始DFS得到的最长路径是一条最长链.由结论[2].B是最长链的一端
至此证毕

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
#define MAXN 10010
int Node,m,n,cnt,ans;
int head[MAXN],dis[MAXN],vis[MAXN],pre[MAXN];
struct node
{
	int u,v,val;
	int next;
}edge[MAXN];
void init()
{
	memset(head,-1,sizeof(head));
	cnt=0;
	for(int i=0;i<10010;i++)
	pre[i]=i;
}
void add(int u,int v,int val)
{
	node E={u,v,val,head[u]};
	edge[cnt]=E;
	head[u]=cnt++;
}
void bfs(int sx)
{
	memset(vis,0,sizeof(vis));
	memset(dis,0,sizeof(dis));
	ans=0;
	queue<int>q;
	Node=sx;
	q.push(Node);
	vis[Node]=1;
	while(!q.empty())
	{
		int u=q.front();
		q.pop();
		for(int i=head[u];i!=-1;i=edge[i].next)
		{
			node E=edge[i];
			if(!vis[E.v])
			{
				vis[E.v]=1;
				dis[E.v]=dis[u]+E.val;
				q.push(E.v);
			}
		}
	}
	for(int i=1;i<=cnt;i++)
	{
		if(ans<dis[i])
		{
			ans=dis[i];
			Node=i;
		}
	}
}
void slove()
{
	bfs(1);
	bfs(Node);
	printf("%d\n",ans);
}
int main()
{
	int a,b,c;
	init();
	while(scanf("%d%d%d",&a,&b,&c)!=EOF)
	{
		add(a,b,c);
		add(b,a,c);
	}
	slove();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/gao506440410/article/details/81428786