Description
After hearing about the epidemic of obesity in the USA, Farmer John wants his cows to get more exercise, so he has committed to create a bovine marathon for his cows to run. The marathon route will include a pair of farms and a path comprised of a sequence of roads between them. Since FJ wants the cows to get as much exercise as possible he wants to find the two farms on his map that are the farthest apart from each other (distance being measured in terms of total length of road on the path between the two farms). Help him determine the distances between this farthest pair of farms.
Input
* Lines 1.....: Same input format as "Navigation Nightmare".
Output
* Line 1: An integer giving the distance between the farthest pair of farms.
Sample Input
7 6
1 6 13 E
6 3 9 E
3 5 7 S
4 1 3 N
2 4 20 W
4 7 2 S
Sample Output
52
有一个树结构, 给你树的所有边(u,v,cost), 表示u和v两点间有一条距离为cost的边. 然后问你该树上最远的两个点的距离是多少?(即树的直径)
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<map>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;
const ll INF=1e18;
const int maxn=50000+5;
const int maxm=100000+5;
//有向边
struct Edge
{
Edge(){}
Edge(int to,int cost,int next):to(to),cost(cost),next(next){}
int to; //边尾部
int cost; //边距离
int next; //指向下条边
}edges[maxm];
int cnt=0; //边总数
int head[maxn];//头结点
//添加两条有向边
void AddEdge(int u,int v,int cost)
{
edges[cnt]=Edge(v,cost,head[u]);
head[u]=cnt++;
edges[cnt]=Edge(u,cost,head[v]);
head[v]=cnt++;
}
//距离
int dist[maxn];
//BFS返回从s出发能到达的最远点编号
int BFS(int s)
{
int max_dist=0;
int id=s;
queue<int> Q;
memset(dist,-1,sizeof(dist));
dist[s]=0;
Q.push(s);
while(!Q.empty())
{
int u=Q.front(); Q.pop();
if(dist[u]>max_dist)
max_dist=dist[id=u];
for(int i=head[u]; i!=-1; i=edges[i].next)
{
Edge &e=edges[i];
if(dist[e.to]==-1)
{
dist[e.to]=dist[u]+e.cost;
Q.push(e.to);
}
}
}
return id;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)==2)
{
cnt=0;
memset(head,-1,sizeof(head));
int u,v,cost;
char c;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d %c",&u,&v,&cost,&c);
AddEdge(u,v,cost);
}
printf("%d\n",dist[BFS(BFS(u))]);
}
return 0;
}