A - Cow Marathon
Time Limit:2000MS Memory Limit:30000KB 64bit IO Format:%lld & %llu
Submit
Status
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<queue>
using namespace std;
const int MAXN=1e6+10;
int head[MAXN],dis[MAXN];
bool vis[MAXN];
int edgenum,n,m,Tnode,ans;
struct Edge{
int from;
int to;
int val;
int next;
}edge[MAXN];
void init()
{
memset(head,-1,sizeof(head));edgenum=0;
}
void addedge(int u,int v,int w)
{
Edge E={u,v,w,head[u]};
edge[edgenum]=E;//另一种方法 赋值号两边类型相同
head[u]=edgenum++;
}
void bfs(int s)
{
memset(dis,0,sizeof(dis)); memset(vis,false,sizeof(vis));
ans=0;
queue<int> que;
que.push(s); vis[s]=true; dis[s]=0; Tnode=s;
while(!que.empty())
{
int now=que.front(); que.pop();
for(int i=head[now];i!=-1;i=edge[i].next )
{
int go=edge[i].to ;
if(!vis[go])
{
// if(dis[go]<dis[now]+edge[i].val)缺省也能过
dis[go]=dis[now]+edge[i].val;
vis[go]=true;
que.push(go);
}
}
}
for(int i=1;i<=m;++i)
{
if(ans<dis[i])
{
ans=dis[i];
Tnode=i;
}
}
}
int main()
{
int i,u,v,w;
char c;
while(~scanf("%d %d",&m,&n))
{
init();//缺省现象:输入结束后没输出且不能再输入 死机状态
for(i=1;i<=n;++i)
{
scanf("%d%d%d %c",&u,&v,&w,&c);
addedge(u,v,w);
addedge(v,u,w);
}
bfs(1);
bfs(Tnode);
printf("%d\n",ans);
}
return 0;
}