首页 > 其他 > 详细

[OI - 模板] 堆优化Dijkstra

时间:2018-11-07 10:23:09      阅读:173      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
 
using namespace std;
//#define DEBUG(x) cerr << #x << "=" << x << endl
const int maxn = 1e6 + 10;

struct Edge
{ 
    int v;
    int w;
    int nxt; 
}e[maxn];

struct node 
{
    int u, d;
    bool operator <(const node& rhs) const 
    {
        return d > rhs.d;
    }
};

int head[maxn], cnt = 0;
int n, m;
int dis[maxn];

inline void addEdge(int u, int v, int w) 
{
    e[++cnt].v = v;
    e[cnt].w = w;
    e[cnt].nxt = head[u];
    head[u] = cnt;
}

inline void Dijkstra() 
{
    for (register int i = 1; i <= n; i++) dis[i] = 0x7fffffff;
    dis[1] = 0;
    priority_queue<node> Q;
    Q.push((node){1,0});    
    while (!Q.empty()) 
    {
        node fr = Q.top(); 
        Q.pop();
        int u = fr.u;
        int d = fr.d;
        if (d != dis[u]) continue;
        for (register int i = head[u]; i; i = e[i].nxt) 
        {
            int v = e[i].v;
            int w = e[i].w;
            if (dis[u] + w < dis[v]) 
            {
                dis[v] = dis[u] + w;
                Q.push((node){v,dis[v]});
            }
        }
    }
}

int main()  
{
    scanf("%d%d", &n, &m);
    for (register int i = 1; i <= m; i++) 
    {
        int x, y, z;
        scanf("%d%d%d", &x, &y, &z);
        addEdge(x, y, z);
        addEdge(y, x, z);
    }
    Dijkstra();
    printf("%d\n", dis[n]);
    return 0;
}

[OI - 模板] 堆优化Dijkstra

原文:https://www.cnblogs.com/aiyi2000/p/9920866.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!