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.

题意:有t条边,n个点,要求求出,1到n的最短距离. 其中边为双向,并且有重边.

看完dijkstra 就来做了这题.

刚开始的代码没有给路双向,也没判断重边,然后搜了些博客都说什么重边重边重边,,,恕我愚钝,你们随笔一句重边 我真的不知道怎么重的

重边:可能存在对一个边输入两次距离,比如说我给个例子,第一行我输入1->3 距离是4 然后第二行又输入了1->3这条边, 距离是9,那么自然1->3 再没有操作之前,题给最短是4 ,所以要判断重边,比较一下.

下面上代码,我会在代码里注释说明

#include<stdio.h>
#include<string.h>
#define M 2000+10
#define inf 0x3f3f3f3f
int t,n;
int book[M];
int dis[M];
int e[M][M];
int main()
{
    int st,ed,dt;
    scanf("%d%d",&t,&n);

    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
        {
            e[i][j]=inf;
            if(i==j)
                e[i][j]=0;
        }

    for(int i=1;i<=t;i++)
    {
        scanf("%d%d%d",&st,&ed,&dt);
        if(dt<e[st][ed])//这就是所谓的重边判断,双向路
            e[st][ed]=dt;
        if(dt<e[ed][st])//这就死所谓的重边判断,双向路
            e[ed][st]=dt;
    }

    for(int i=1;i<=n;i++)
        dis[i]=e[1][i];

    for(int i=1;i<=n;i++)
    {
        int minn=inf;
        int u=1;
        for(int j=1;j<=n;j++)
        {
            if(!book[j]&&dis[j]<minn)
            {
                minn=dis[j];
                u=j;
            }
        }
        book[u]=1;
        for(int v=1;v<=n;v++)
        {
            if(dis[v]>dis[u]+e[u][v])
                dis[v]=dis[u]+e[u][v];
        }
    }
    printf("%d\n",dis[n]);
}
/*路为双向,重边问题.
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

4 4
1 3 10
2 3 10
3 4 5
4 1 1
*/

    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/weixin_41075012/article/details/80072175
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞