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 Input
22
题目翻译
描述
在遥远的北方社区之间修建和维护道路是一项昂贵的业务。考虑到这一点,道路的修建使得从一个村庄到一个村庄只有一条路线,而不会两次穿过其他村庄。
Given是一个位于遥远北方的地区,由许多村庄和道路组成,因此任何其他村庄都可以通过道路到达任何村庄。你的工作是找出该地区两个最偏远村庄之间的道路距离。
该地区有多达10000个村庄通过路段连接。这些村庄从1开始编号。
输入
问题的输入是一系列线,每条线包含三个正整数:一个村庄的数量、不同村庄的数量以及连接村庄的路段长度(以公里为单位),所有路段都是双向的。
输出
你要输出一个整数:该地区两个最偏远村庄之间的道路距离。
解析
(待更新)
代码
#include<bits/stdc++.h>
using namespace std;
struct Edge
{
int to,next,mon;
}edge[40505];
struct code
{
int cod,len;
};
int head[40505],tot=0,maxDep,l1;
bool vis[40505];
void add(int from,int to,int mon)
{
edge[tot].to=to;
edge[tot].mon=mon;
edge[tot].next=head[from];
head[from]=tot;
++tot;
}
void bfs(int start)
{
queue<code> a;
a.push(code{start,0});
while(a.size())
{
code u=a.front();
a.pop();
if(u.len>maxDep)
{
maxDep=u.len;
l1=u.cod;
}
vis[u.cod]=1;
for(int i=head[u.cod];i!=-1;i=edge[i].next)
{
if(!vis[edge[i].to])
{
a.push(code{edge[i].to,u.len+edge[i].mon});
}
}
}
}
int main()
{
int n,m=0,from,to,mon,maxlen=0;// n:点数 m:线数
memset(head,-1,sizeof(head));
while(cin>>from>>to>>mon)
{
add(from,to,mon);
add(to,from,mon);
m+=2;
if(from>n)n=from;
if(to>n)n=to;
}
bfs(1);
memset(vis,0,sizeof(vis));
maxDep=0;
bfs(l1);
cout<<maxDep;
return 0;
}