SPFA算法

2024-08-14

采用SPFA算法,求解图中两点间的最短距离

#include <bits/stdc++.h>
#define io cin.tie(0), cout.tie(0), ios::sync_with_stdio(false)
#define LL long long
#define ULL unsigned long long
#define EPS 1e-8
#define INF 0x7fffffff
#define SUB -INF - 1
using namespace std;
const int N = 100005, M = 200005;
int n, m;
int pre[N];
void print_path(int s, int t)
{
    if (s == t)
    {
        printf("%d", s);
        return;
    }
    print_path(s, pre[t]);
    printf("%d", t);
}
int head[N], cnt;
struct
{
    int to, next, w;
} edge[M];
void init()
{
    for (int i = 0; i < N; i++)
        head[i] = -1;
    for (int i = 0; i < M; i++)
        edge[i].next = -1;
    cnt = 0;
}
void addedge(int u, int v, int w)
{
    edge[cnt].to = v;
    edge[cnt].w = w;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}
int dis[N];
bool inq[N];
int Neg[N];
int spfa(int s)
{
    memset(Neg, 0, sizeof(Neg));
    Neg[s] = 1;
    for (int i = 1; i <= n; i++)
    {
        dis[i] = INF;
        inq[i] = false;
    }
    dis[s] = 0;
    queue<int> Q;
    Q.push(s);
    inq[s] = true;
    while (!Q.empty())
    {
        int u = Q.front();
        Q.pop();
        inq[u] = false;
        for (int i = head[u]; ~i; i = edge[i].next)
        {
            int v = edge[i].to, w = edge[i].w;
            if (dis[u] + w < dis[v])
            {
                dis[v] = dis[u] + w;
                pre[v] = u;
                if (!inq[v])
                {
                    inq[v] = true;
                    Q.push(v);
                    Neg[v]++;
                    if (Neg[v] > n)
                        return 1;
                }
            }
        }
    }
    return 0;
}
int main()
{
    while (~scanf("%d%d", &n, &m))
    {
        init();
        if (n == 0 && m == 0)
            return 0;
        while (m--)
        {
            int u, v, w;
            scanf("%d%d%d", &u, &v, &w);
            addedge(u, v, w);
            addedge(v, u, w);
        }
        spfa(1);
        printf("%d\n", dis[n]);
        printf("path:");
        print_path(1, n);
        printf("\n");
    }
    return 0;
}