AcWing:堆优化版dijkstra算法

/*堆优化版dijkstra算法*/
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
#include <vector>
using namespace std;
const int maxsize = 150005;
int n, m;
/*在邻接表里:第一个int为结点编号,第二个为边值*/
typedef  pair<int, int> PII;             
/*在队列里:第一个int为起点到该点的最短距离,第二个int为结点编号*/
vector<PII> graph[maxsize];         //邻接表
int dist[maxsize];                  //最短距离
bool st[maxsize];                   //访问flag

int dijkstra(int u)
{
    priority_queue<PII, vector<PII>, greater<PII>> heap;        //优先队列,距离小的在前
    memset(dist, 0x3f, sizeof dist);
    dist[u] = 0;
    heap.push({0, 1});
    while(heap.size())
    {
        PII temp = heap.top();
        heap.pop();

        int val = temp.first, vex = temp.second;

        if(st[vex]) continue;                                   //该点已经访问过了,直接重新循环

        st[vex] = true;

        for(int i = 0; i < graph[vex].size(); i++)
        {
            int j = graph[vex][i].first;                        //获取邻接表的顶点
            if(dist[j] > val + graph[vex][i].second)            //新引入点的距离+边值 小于 邻接顶点的最小距离
            {
                dist[j] = val + graph[vex][i].second;
                heap.push({dist[j], j});
            }
        }

    }
    if(dist[n] == 0x3f3f3f3f) return -1;
    else return dist[n];

}

int main()
{
    int a, b, c;
    ios::sync_with_stdio(false);        //关掉输入输出同步
    cin >> n >> m;
    for(int i = 0; i < m; i++)
    {
        cin >> a >> b >> c;
        graph[a].push_back({b, c});
    }

    cout << dijkstra(1) << endl;

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值