Til the Cows Come Home (Dijkstra)

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

* Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.
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
Hint
INPUT DETAILS:

There are five landmarks.

OUTPUT DETAILS:

Bessie can get home by following trails 4, 3, 2, and 1.

题意:

美丽的Bessie要回谷仓(标号为1)睡一个美容觉,因为她的老公要在早上叫醒她去牛场(标号为n)挤晨奶,

因此为了睡到时间更长,她必须尽快从点n回到点1,求出最短距离

第一行 输入T,N,T为边关系的数量,N为出发点和点的总数(开始输入顺序反了,测试样例对,可是一直wa,血的教训啊

接下来T行,每行3个数据,前两个为点的标号,第3个为两点的距离

思路:

从点n出发到点1,可以看出是单源最短路问题,可以用Dijkstra算法,

因为有重边,所以在存边关系时要筛选出两点的最短距离(所以以后再处理这种问题在存边关系时就筛选出两点的最点距离)

代码:

#include
#include
using namespace std;
#define inf 99999999
int e[10000][10000];  // 存放边关系
int book[10000000];     //记录那些点已经是确定值,即离源点最近
int dis[10100000];      //记录到源点的距离
int main(){
    int n,t;
    scanf("%d%d",&t,&n);
    int i,j;
    for(i=0;i<=n;i++){      //初始化边关系,即到自己的距离是0 ,到其他点的距离是无穷大
        for(j=0;j<=n;j++)
            if(i==j) e[i][j]=0;
            else e[i][j]=inf;
    }
    memset(book,0,sizeof(book));
    for(i=1;i<=t;i++){      //读取边关系
        int t1,t2,t3;
        scanf("%d%d%d",&t1,&t2,&t3);//t1,t2为两端点,t3 为权值(距离)
        if(t3t2 t2-->t1 的距离一样
            e[t2][t1]=t3;
        }

    }
    for(i=1;i<=n;i++)      //初始化n 点到任意点的距离
        dis[i]=e[n][i];
    book[n]=1;
    for(i=1;i<=n-1;i++){
        int min=inf,u=n;
        for(j=1;j<=n;j++){   //找距离 n 最近的点
            if(book[j]==0&&dis[j]e[u][j]+dis[u]){  //判断 n-->j的距离是否大于 n-->u-->j 的距离和
                    dis[j]=e[u][j]+dis[u];  //如果大于,则更新最小值(n到j的最短距离是先经过u再到j)
                }
            }
        }
    }
   /* for(i=1;i<=n;i++)
        printf("I %d : %d\n",i,dis[i]);*/
    printf("%d\n",dis[1]);
return 0;
}



你可能感兴趣的:(最短路径)