Cow Marathon
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 4962 | Accepted: 2414 | |
Case Time Limit: 1000MS |
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
Hint
The longest marathon runs from farm 2 via roads 4, 1, 6 and 3 to farm 5 and is of length 20+3+13+9+7=52.
详细解析,请看:点击打开题目
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define MAX 40000
int n,m;
vector<int> link[MAX+10];
vector<int> va[MAX+10];
bool vis[MAX+10];
int dis[MAX+10];
void init()
{
for(int i=1;i<=n;i++)
{
link[i].clear();
va[i].clear();
}
}
int bfs(int x)
{
int ans;
int maxx=0;
memset(vis,false,sizeof(vis));
memset(dis,0,sizeof(dis));
queue<int> q;
dis[x]=0;
q.push(x);
vis[x]=true;
while(!q.empty())
{
int st=q.front();
q.pop();
for(int i=0;i<link[st].size();i++)
{
if(!vis[link[st][i]])
{
q.push(link[st][i]);
dis[link[st][i]]=dis[st]+va[st][i];
if(maxx<dis[link[st][i]])
{
maxx=dis[link[st][i]];
ans=link[st][i];
}
vis[link[st][i]]=true;
}
}
}
return ans;
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
init();
for(int i=1;i<=m;i++)
{
int t1,t2,t3;
char t4[3];
scanf("%d %d %d %s",&t1,&t2,&t3,t4);
link[t1].push_back(t2);
va[t1].push_back(t3);
link[t2].push_back(t1);
va[t2].push_back(t3);
}
int z=bfs(1);
int ans=bfs(z);
printf("%d\n",dis[ans]);
}
return 0;
}