A - Cow Marathon POJ-1985

本文介绍了一个寻找农场间最长路径的算法实现,通过构建图并使用广度优先搜索算法找到两个最远农场之间的距离,适用于解决类似迷宫路径寻找的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
 } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值