spfa求最短路

思路:

(1)存图:由于是稀疏图,故用邻接表存储,w[]同步存权值

(2)由于带负权求最短路,于是考虑spfa()算法,st[]同步标记是否在队列中。

(3)spfa算法:

  1. 初始化,dist[]初始化为无穷,起点初始化为0,队列里放入起点,起点设为在队列中。
  2. 不断拿出队头元素t,并标记为不在队列里,遍历与t相连的所有节点j,如果能缩短更新距离,就更新距离;更新后如果j不在队列中,就放在队列中以备用。
  3. 最后判定,如果dist[n] == 0x3f3f3f3f即未被更新过,则为不可达;反之则为可达。

代码:

#include<bits/stdc++.h>

using namespace std;

const int N = 150000;

int n,m;
int h[N],st[N],e[N],ne[N],idx,dist[N],w[N];
typedef pair<int,int> PII;

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

void spfa()
{
    memset(dist,0x3f,sizeof dist);
    dist[1] = 0;
    
    queue<int> q;
    q.push(1);
    
    while(!q.empty())
    {
        auto 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])
                {
                    q.push(j);
                    st[j] = 1;
                }
            }
        }
    }
    
    if(dist[n] == 0x3f3f3f3f) puts("impossible");
    else
        cout << dist[n] << endl;
    
}

int main()
{
    
    memset(h,-1,sizeof h);
    cin >> n >> m;
    
    while(m --)
    {
        int a,b,c;
        cin >> a >> b >> c;
        
        add(a,b,c);
    }
    
    spfa();
    
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

y_lov

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值