851. spfa求最短路

AcWing题目链接

SPFA

使用队列来保存更新过的顶点(栈或者优先队列也可以)。只有更新过的顶点才会产生松弛操作。

#include <iostream>
#include <vector>
#include <algorithm> 
#include <cmath>
#include <cstring>
#include <queue>
#include <unordered_map>
using namespace std;
const int N = 100010;
const int INF = 0x3f3f3f3f;

int n, m;
int d[N];
bool st[N]={false};
int idx = 0 ;
int h[N], ne[N], e[N], w[N]; //邻接表
void add(int a, int b, int c){
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;  //其实是倒着遍历的 类似于链串起来,然后倒着查回去
}
int spfa(int s){
    memset(d, 0x3f, sizeof d);
    d[s] = 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(d[j] > d[t]+ w[i]){
                d[j] = d[t]+ w[i];
                if(!st[j]){
                    q.push(j);
                    st[j] = true;
                }
            }
        }
        
    }
    if(d[n] == 0x3f3f3f3f) return -1;
    else return d[n];
}

int main(){
    scanf("%d%d", &n, &m);
    int u, v, w;
    memset(h, -1, sizeof h);
    for(int i = 0; i < m; i++){
        scanf("%d%d%d", &u, &v, &w);
        add(u, v, w); //重边 自环都没影响
    }
    int t = spfa(1);
    if(t==-1) puts("impossible");
    else printf("%d\n", t);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值