Til the Cows Come Home

Til the Cows Come Home

Description
Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible.
Farmer John’s field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.
Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.

Input
Line 1: Two integers: T and N

Output
* Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.

Sample Input
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

Sample Output
90

单源最短路问题,用dijsktra时要注意:
- 无向图
- 可能有重边
这道题我一直WA,原因是INF设置的太小了,应该大于2000*100的。也因此学习了无穷大常量的设置方法:
- const int INF =0x7fffffff;//32位int的最大值
- const int INF=0x3f3f3f3f;//常用的无穷大常量,避免松弛操作溢出,且可以用memset初开始化:memset(map,0x3f,sizeof(map));

这道题的代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<limits>

using namespace std;
const int INF=0x3f3f3f3f;//最大值要>=2000*100
const int MAXN=1005;
int gra[MAXN][MAXN],d[MAXN],vis[MAXN];
int t,n;
void dij(int u);
int main()
{
    while(~scanf("%d%d",&t,&n)){
        int i,j,k;
        int a,b,c;
        //printf("%d\n",INF);
        for(i=0;i<n;i++){
            for(j=0;j<n;j++){
                gra[i][j]=INF;
            }
        }
        for(i=0;i<t;i++){
            cin>>a>>b>>c;
            ///无向图且可能有重边
            if(gra[a-1][b-1]>c){
                gra[a-1][b-1]=c;
                gra[b-1][a-1]=c;
            }

        }
        dij(0);
        printf("%d\n",d[n-1]);
    }
    return 0;
}
void dij(int u)
{
    int tag;
    int i,j,k;
    memset(vis,0,sizeof(vis));
    for(i=0;i<n;i++){d[i]=INF;}
    d[u]=0;
    d[1002]=INF;
    for(i=0;i<n;i++){
        tag=1002;
        for(j=0;j<n;j++){
            if(!vis[j]&&d[j]<d[tag]){
                tag=j;
            }
        }
        vis[tag]=1;
        for(k=0;k<n;k++){
            if(!vis[k])
                d[k]=min(d[k],(d[tag]+gra[tag][k]));
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值