其他分享
首页 > 其他分享> > 【spfa】AcWing851.spfa求最短路——模板题

【spfa】AcWing851.spfa求最短路——模板题

作者:互联网

AcWing851.spfa求最短路

题解

spfa算法即为Bellman-Ford的优化,只有每次dist[a]发生了变化才需要更新对应的dist[b],通过此减少循环次数

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

const int N = 1e5 + 10;

bool st[N];
int dist[N];
int h[N], e[N], v[N], ne[N], idx;
int n, m;

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

void spfa()
{
    dist[1] = 0;
    queue<int> q;
    q.push(1);
    st[1] = true;
    while(q.size())
    {
        int t = q.front();
        q.pop();
        st[t] = false;
        for(int i = h[t]; ~i; i = ne[i])
            if(dist[e[i]] > dist[t] + v[i])
                {
                    dist[e[i]] = dist[t] + v[i];
                    if(!st[e[i]]) q.push(e[i]), st[e[i]] = true ;
                }
    }
}

int main()
{
    memset(dist, 0x3f, sizeof dist);
    memset(h, -1, sizeof h);
    cin >> n >> m;
    int a, b,  c;
    for(int i = 0; i < m; ++i)
    {
        cin >> a >> b >> c;
        add(a, b, c);
    }
    spfa();
    if(dist[n] == 0x3f3f3f3f) cout << "impossible" << endl;
    else cout << dist[n] << endl;
    return 0;
}

标签:dist,idx,int,ne,st,spfa,AcWing851,模板
来源: https://www.cnblogs.com/czy-algorithm/p/16324012.html