poj 2631 Roads in the North (*树的直径)

Roads in the North
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 4513   Accepted: 2157

Description

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

题目大意:

求树中任意两点最短路长度的最大值。

求树的直径模板题。

还是因为室友的数据结构作业,我才知道有这么个问题。

假设有这么个直径st,s是起点,t是终点。先求任一点到所有其他点的距离,则距离该点最远的点一定在直径上,否则该点就是直径了。再从这个最远的点出发,求该点到所有点的距离,则此次最远的点和上次最远的点必定一个是s,一个是t。

做两次bfs就好了。(树上的单源最短路可以O(n)时间内解决)

#include<cstdio>
#include<queue>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<string>
#include<iostream>
#define ll long long
#define maxn 10000 int to[maxn*+];
int w[maxn*+];
int next[maxn*+];
int head[maxn+]; struct tnode
{
int point;
int dis;
};
int vis[maxn+]; int main()
{
int cnt=;
memset(head,-,sizeof(vis));
int a,b,c;
while(scanf("%d%d%d",&a,&b,&c)!=EOF)
{
to[cnt]=b;w[cnt]=c;next[cnt]=head[a];head[a]=cnt++;
to[cnt]=a;w[cnt]=c;next[cnt]=head[b];head[b]=cnt++;
} std::queue<tnode> q;
memset(vis,,sizeof(vis));
q.push((tnode){,});
vis[]=;
int far=,farp=;
while(!q.empty())
{
tnode node=q.front();q.pop();
if(node.dis>far)
{
far=node.dis;
farp=node.point;
}
for(int i=head[node.point];i!=-;i=next[i])
{
if(!vis[to[i]])
{
q.push((tnode){to[i],node.dis+w[i]});
vis[to[i]]=;
}
}
} memset(vis,,sizeof(vis));
q.push((tnode){farp,});
vis[farp]=;
int ans=;
while(!q.empty())
{
tnode node=q.front();q.pop();
ans=std::max(ans,node.dis);
for(int i=head[node.point];i!=-;i=next[i])
{
if(!vis[to[i]])
{
q.push((tnode){to[i],node.dis+w[i]});
vis[to[i]]=;
}
}
} printf("%d\n",ans); return ;
}
上一篇:题解报告:poj 2631 Roads in the North(最长链)


下一篇:Java Swing界面编程(5)---JLabel中设置图片