【模板】单源最短路 dijistra 优先队列

$Abyssful$大菜鸡看了一下午代码p都没打。

P4779 【模板】单源最短路径(标准版)

一遍a掉了,回忆起来了结构体、stl的优先队列种种,写代码真有趣啊。

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

int n, m;

struct Node {
    int v, nex, w;
    Node(int v = 0, int nex = 0, int w = 0) :
        v(v), nex(nex), w(w) { }
} Edge[200005];

int h[100005], stot;
void add(int u, int v, int w) {
    Edge[++stot] = Node(v, h[u], w);
    h[u] = stot;
}

struct QAQ {
    ll dis; int u;
    QAQ(int u = 0, ll dis = 0) :
        u(u), dis(dis) { }
    bool operator < (const QAQ a) const {
        return dis > a.dis;
    }    
};

int s, flag[100005];
ll dis[100005];
void diji() {
    priority_queue <QAQ> q;
    for(int i = 1; i <= n; i ++)    dis[i] = oo;
    dis[s] = 0;
    q.push(QAQ(s, 0));
    while(!q.empty()) {
        QAQ u = q.top();    q.pop();
        if(flag[u.u])    continue;
        for(int i = h[u.u]; i; i = Edge[i].nex) {
            int v = Edge[i].v;
            if(!flag[v] && dis[u.u] + Edge[i].w < dis[v]) {
                dis[v] = dis[u.u] + Edge[i].w;
                q.push(QAQ(v, dis[v]));
            }
        }
        flag[u.u] = 1;
    }
}

int main() {
    scanf("%d%d%d", &n, &m, &s);
    for(int i = 1; i <= m; i ++) {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }
    diji();
    for(int i = 1; i <= n; i ++)    printf("%lld ", dis[i]);
}

 

posted @ 2020-09-04 16:33  Wans_ovo  阅读(190)  评论(0编辑  收藏  举报