天天看點

# SPFA算法:求最短路

文章目錄

          • 思路
          • 大緻模闆
          • 例題
# SPFA算法:求最短路
注意:==超級容易被卡!==沒有負權邊千萬千萬别用,用堆優化的DJ!!!
思路

優化Bellman-Ford

對Bellman-Ford算法 中的

dist[b] = min(dist[b], dist[a] + w )

做優化。

因為dist[a]不一定會更新dist[b]。具體而言就是,當

dist[a]

變小了, 與其相連的dist[b]才會變小。

用寬搜做優化。

大緻模闆
*1 定義一個

queue q

, 用來儲存dist變小了的點;

*2 while q 不空

*3 取出隊頭 t,pop(t);

*4 更新 t 的所有出邊。

*5 如果更新成功 且 隊列中沒有b, 将 b 入隊;

寫法和Dijkstra算法很像,不過是把針對“點”的操作 改為 針對“邊”的操作。

注:很多正權圖可以用SPFA。

例題

Acwing 851. spfa求最短路

#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, m;
int dist[N];
int ne[N], h[N], e[N], w[N], idx = 0;
bool st[N];

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

int spfa(){
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    st[1] = 1;
    
    queue<int> q;
    q.push(1);
    
    while(q.size()){
        int t = q.front();
        q.pop();
        st[t] = 0;
        
        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] = 1;
                    q.push(j);
                }
            }
        }
    }
    if(dist[n] == 0x3f3f3f3f) return -1;
    return dist[n];
}

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

————————————————————————————————————