SPFA算法模板

简介

SPFA 算法是 Bellman-Ford算法 的队列优化算法的别称,通常用于求含负权边的单源最短路径,以及判负权环。SPFA 最坏情况下时间复杂度和朴素 Bellman-Ford 相同,为 O(VE)。

代码

求最短路版(和dijkstra堆优化有点类似)
//spfa求最短路
#include <bits/stdc++.h>

using namespace std;

const int N = 100010;
int e[N], ne[N], h[N], w[N], idx;
int n, m, dist[N];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}

int spfa()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;

    queue<int> qu;
    qu.push(1);
    st[1] = true;

    while (!qu.empty())
    {
        int t = qu.front();
        qu.pop();
        st[t] = false;

        for (int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > dist[t] + w[i])
            {
                dist[j] = dist[t] + w[i];
                if (!st[j])
                {
                    st[j] = true;
                    qu.push(j);
                }
            }
        }
    }

    return dist[n];
}

int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for (int i = 1; i <= m; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }

    spfa();

    if (dist[n] == 0x3f3f3f3f)
        puts("impossible");
    else
        cout << dist[n] << endl;
    return 0;
}
判断负环版

我们需要注意的是加上判断负环的话,时间复杂度可能就会比较高

#include <bits/stdc++.h>

using namespace std;

const int N = 100010;
int e[N], ne[N], h[N], w[N], idx;
int n, m, dist[N], cnt[N];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}

int spfa()
{
    queue<int> qu;
    for(int i = 1; i <= n; i++)//因为是判断图中是否存在负环,而不是看单一的点,故而在遍历的时候我们首先要把所有的点都放到队列中
    {
        st[i] = true;
        qu.push(i);
    }

    while (!qu.empty())
    {
        int t = qu.front();
        qu.pop();
        st[t] = false;

        for (int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > dist[t] + w[i])
            {
                dist[j] = dist[t] + w[i];
                cnt[j] = cnt[t] + 1;
                if(cnt[j] >= n) return true;//(抽屉原理,当cnt>=n时一定遍历了大于等于n+1个点,由抽屉原理可知一定重复遍历了一些点,那么就存在负环)
                if (!st[j])
                {
                    st[j] = true;
                    qu.push(j);
                }
            }
        }
    }

    return false;
}

int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for (int i = 1; i <= m; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }

    if (spfa())
        puts("Yes");
    else
        puts("No");
	
	return 0;
}
  • 13
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值