蓝桥-算法训练 ALGO-5 最短路【SPFA | 模板】

本文介绍了一种用于解决带负权边的最短路径问题的SPFA算法。该算法适用于有向图,且图中可能存在负权边但无负权环的情况。通过实例代码详细解析了SPFA算法的实现细节,并提供了完整的AC代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

题目描述:

给定一个n个顶点,m条边的有向图(其中某些边权可能为负,但保证没有负环)。请你计算从1号点到其他点的最短路(顶点从1到n编号)。
1 <= n <= 20000,1 <= m <= 200000,-10000 <= len <= 10000,保证从任意顶点都能到达其他所有顶点。

SPFA:

  1. 边权存在负数时不能用Dijkstra。
  2. 判断负圈:如果一个点进队列超过 n 次,则说明图中存在负圈 (代码中neg数组)。

注意:

  1. 如果是双向边的话链式前向星需要开两倍空间。
  2. 还要注意边的数量,不能想当然为 N 。

AC Codes:

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
//#include <unordered_set>
//#include <unordered_map>
#include <deque>
#include <list>
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
//#pragma GCC optimize(2)
using namespace std;
typedef long long ll;
//cout << fixed << setprecision(2);
//cout << setw(2);
const int N = 2e4 + 6, M = 2e5 + 5, INF = 0x3f3f3f3f;

int n, m;
int dis[N], inq[N], neg[N];
int head[N], Next[M], ver[M], edge[M], tot;
void add(int u, int v, int w) {
    ver[++tot] = v, edge[tot] = w;
    Next[tot] = head[u], head[u] = tot;
}

bool SPFA() {
    queue<int> q;
    memset(dis, 0x3f, sizeof(dis));
    q.push(1);
    neg[1] = inq[1] = 1, dis[1] = 0;
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        inq[x] = 0;
        for (int i = head[x]; i; i = Next[i]) {
            int y = ver[i], w = edge[i];
            if (dis[x] + w < dis[y]) {
                dis[y] = dis[x] + w;
                if (!inq[y]) {
                    q.push(y);
                    inq[y] = 1;
                    neg[y]++;
                    if (neg[y] > n) return true;
                }
            }
        }
    }
    return false;
}

int main() {
    //freopen("/Users/xumingfei/Desktop/ACM/test.txt", "r", stdin);
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    cin >> n >> m;
    tot = 1;
    for (int i = 0; i < m; i++) {
        int x, y, z;
        cin >> x >> y >> z;
        add(x, y, z);
    }
    SPFA();
    for (int i = 2; i <= n; i++) cout << dis[i] << '\n';
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值