image

#include <bits/stdc++.h>
using namespace std;

const int N = 510;                        //+10比较有安全感

int n, m;
int g[N][N]; //邻接矩阵存储
int dist[N]; //1----n的最短路
bool st[N];  //标记是否被用过

int dijkstra()
{
    memset(dist, 0x3f, sizeof dist); //求最大值时,初始化为+无穷
    dist[1] = 0;

    for (int i = 0; i < n - 1; i ++ ) //n个点,求最短路n-1次循环
    {
        int t = -1;
        for (int j = 1; j <= n; j ++ ) // 不在s中的距离最近的点 
            if (!st[j] && (t == -1 || dist[t] > dist[j])) //满足松弛最后一段(第二段)的条件时
                t = j; //用j更新t

        for (int j = 1; j <= n; j ++ )
            dist[j] = min(dist[j], dist[t] + g[t][j]); //求直接到达和间接到达的最短路

        st[t] = true; //标记用过的
    }

    if (dist[n] == 0x3f3f3f3f) return -1; //当未被更新,即无最短路时
    return dist[n];
}

int main()
{
    scanf("%d%d", &n, &m);

    memset(g, 0x3f, sizeof g); //初始化最短路为+无穷
    while (m -- )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);

        g[a][b] = min(g[a][b], c); //间接解决重边问题,自环不用存
    }

    printf("%d\n", dijkstra());

    return 0;
}

1 comments

  • @ 2024-8-21 14:46:49

    我拿你代码交了一遍,过了啊,你再交一遍吧,代码没问题

    🤣 2
    • 1