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
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
题意:农场主想让他的牛得到锻炼,于是就想要让他的牛在最远的两个农场之间奔跑,给你农场之间的距离,问农场间最远距离是多少
思路:树的直径两个bfs求出最远距离,后面的字母不用管,干扰选项,注意输入字符的时候要getchar()吸取回车。wa了一次是因为数组开小了,差不多开到八九万就可以了。
代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
#define MAXN 91000
struct st{
int from;
int to;
int val;
int next;
}shu[MAXN*2];
int head[MAXN];
int edgenum;
void addedge(int u,int v,int w){
shu[edgenum].from=u;
shu[edgenum].to=v;
shu[edgenum].val=w;
shu[edgenum].next=head[u];
head[u]=edgenum++;
}
int ans;
int Tnode;
int dist[MAXN];
int vis[MAXN];
int n;
void bfs(int s){
memset(dist, 0, sizeof(dist));
memset(vis,0, sizeof(vis));
queue<int >q;
q.push(s);
ans=0;
Tnode=s;
vis[s]=1;dist[s]=0;ans=0;
while(!q.empty())
{
int u=q.front();
q.pop();
for(int i=head[u];i!=-1;i=shu[i].next)
{
int v=shu[i].to;
if(!vis[v]&&dist[v]<dist[u]+shu[i].val)
{
vis[v]=1;
dist[v]=dist[u]+shu[i].val;
if(ans<dist[v])
{
ans=dist[v];
Tnode=v;
}
q.push(v);
}
}
}
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
memset(head,-1,sizeof(head));
edgenum=0;
for(int i=0;i<m;i++)
{
int a,b,c;
char h;
scanf("%d%d%d%c",&a,&b,&c,&h);
getchar();
addedge(a-1,b-1,c);
addedge(b-1,a-1,c);
}
bfs(0);
bfs(Tnode);
printf("%d\n",ans);
}
return 0;
}