Roads in the North 树的直径 1 Sec

2 篇文章 0 订阅
1 篇文章 0 订阅
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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值