spfa求最短路径

#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;

const int N = 1e6 + 100;

int h[N], ne[N], w[N], e[N], idx, dis[N], st[N];
int n, m;


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

int spfa()
{
    memset(dis, 0x3f, sizeof dis);
    queue<int> Q;
    Q.push(1);
    st[1] = 1;
    dis[1] = 0;
    while(Q.size())
    {
        int head = Q.front();
        Q.pop();
        st[head] = 0;
        for(int j = h[head]; ~j; j = ne[j])
        {
            int x = e[j];
            if(dis[x] > dis[head] + w[j])
            {
                dis[x] = dis[head] + w[j];
                if(st[x] == 0)
                {
                    Q.push(x);
                    st[x] = 1;
                }
            }
        }
    }
    if(dis[n] > inf / 2) return -1;  //dis[n] 大于 inf/2 说明没有路径
    else return dis[n];
}

int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> m;
    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) puts("impossible");
    else cout << dis[n];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值