Til the Cows Come Home

来源:互联网 发布:天下x天下 人祸和知彼 编辑:程序博客网 时间:2024/06/06 01:05

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*100const 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]));        }    }}
0 0
原创粉丝点击