851. spfa求最短路(用佇列優化bellman——ford演算法)

H_L__發表於2020-09-26

在這裡插入圖片描述

#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>

using namespace std;

const int N = 100010;

int h[N],e[N],ne[N],w[N], idx;

bool st[N];//判斷這個點是否已經在佇列中

int dist[N];

int n, m;

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;
    
    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 != -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;
                    q.push(j);
                }
            }
        }
    }
    
    if(dist[n] > 0x3f3f3f3f / 2) return -1;
    return dist[n];
}

int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    
    while(m --)
    {
        int a, b, c;
        cin >>a >> b >> c;
        
        add(a, b, c);
    }
    
    if(spfa() == -1) cout << "impossible";
    else cout << spfa();
    
    return 0;
}//來自acwing

相關文章