spfa求最短路

spfa求最短路

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10;

int h[N], e[N], ne[N], w[N], idx;
int n, m;
int dis[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++;
}
void spfa(){
    memset(dis, 0x3f, sizeof dis);
    dis[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(dis[j] > dis[t] + w[i]){
                dis[j] = dis[t] + w[i];
                if(!st[j]){
                    st[j] = true;
                    q.push(j);
                }
            }
        }
    }
}
signed main(){
    memset(h, -1, sizeof h);
    scanf("%d%d", &n, &m);
    
    while(m--){
        int a, b, c; scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }
    spfa();
    
    if(dis[n] >= 0x3f3f3f3f / 2) cout << "impossible" << endl;
    else cout << dis[n] << endl;
    
    return 0;
}
posted @ 2025-04-07 20:07  awei040519  阅读(19)  评论(0)    收藏  举报