最短路径之dijkstra算法(单源最短路)(堆优化,适用于稀疏图)

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

using namespace std;

const int N = 150000,M=N*2;

typedef pair<int, int> PII;

int h[N], e[M], w[M], ne[M], idx;
int dist[N];
bool st[N];
int n,m;

void add(int a, int b, int c)  // 添加一条边a->b,边权为c
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

int dijkstra()
{
    memset(dist,0x3f,sizeof dist);
    
    priority_queue<PII,vector<PII>,greater<PII>> ans;//建立小根堆,减少搜索过程
    
    ans.push({0,1});//first存储当前节点到源点的距离,second存储当前节点,从源点开始遍历
    dist[1]=0;
    while(ans.size())
    {
        auto az=ans.top();//堆的顶部是最小节点
        ans.pop();
        int x=az.second,y=az.first;
        
        if(st[x]) continue;//如果该节点被遍历过则返回
        st[x]=true;
        
        for(int i=h[x];i!=-1;i=ne[i])
        {
            int t=e[i];
            if(dist[t]>y+w[i])//与朴素版dijkstra算法同理
            {
                dist[t]=y+w[i];
                ans.push({dist[t],t});//拓展点
            }
        }
        
    }
    if(dist[n]==0x3f3f3f3f)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);
    }
    int t=dijkstra();
    
    cout<<t<<endl;
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

璀璨的秋叶

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

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

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

打赏作者

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

抵扣说明:

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

余额充值