SPFA算法

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

#define INF 0x3f3f3f3f
const int N = 3000;        // N为定点数,邻接矩阵中 N 一般不要超过5000,否则会存在内存问题
int n, m;
int g[N][N], dist[N];
bool st[N];
queue<int> q;

void spfa(){
    st[1] = true;
    dist[1] = 0;
    q.push(1);
    while (q.size()) {
        int t = q.front();
        q.pop();
        st[t] = false;
        for (int i = 1; i <= n; i++) {
            if (dist[i] > dist[t] + g[t][i]) {   // 这里的判断条件需根据实际情况,并不是完全固定的,如Acwing - 920最优乘车
                dist[i] = dist[t] + g[t][i];
            //  pre[i] = t;                         // 用于记录前驱节点(记录路径)
                if (!st[i]) {
                    q.push(i);
                    st[i] = true;
                }
            }
        }
    }
}

int main() {
    cin >> n >> m;
    memset(g, 0x3f, sizeof g);
    memset(dist, 0x3f, sizeof dist);
    int a, b, c;
    while (m--) {
        cin >> a >> b >> c;
        g[a][b] = g[b][a] = min(g[a][b], c);    //无向图
        // g[a][b] = min(g[a][b], c);            //有向图
    }
    spfa();
    if (dist[n] == INF) puts("impossible");
    else printf("%d", dist[n]);
    
    /** 记录路径操作 */
    stack<int> help;    //遍历前驱节点,压入栈中,再取出来时可以变为正序的
    for (int i = n; ~i; i=pre[i]) help.push(i);    // n为路径终点
    while (help.size()) {
        printf("%d ", help.top());
        help.pop();
    }
}

 

posted @ 2023-05-19 01:24  刘海烽  阅读(38)  评论(0)    收藏  举报