码迷,mamicode.com
首页 > 其他好文 > 详细

Dijkstra

时间:2018-01-28 12:46:22      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:tor   tchar   stream   namespace   ring   temp   air   return   head   

ddd

ddd

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<iostream>
#define MAXN 500010
#define oo 2147483647

using namespace std;

int head[MAXN * 2],dis[MAXN],tot,n,m,s;
bool vis[MAXN];

typedef pair<int, int> pir;

struct Edge {
    int node;
    int next;
    int value;
}e[MAXN];

inline void add(int x,int y,int z) {
    e[++tot].node = y; e[tot].value = z; e[tot].next = head[x]; head[x] = tot;
}

priority_queue<pir, vector<pir>, greater<pir> > que;

void dijkstra(int s) {
    dis[s] = 0;
    que.push(make_pair(dis[s], s));
    while (!que.empty()) {
        pir temp = que.top();
        que.pop();
        int x = temp.second;
        if (!vis[x]) {
            vis[x] = true;
            for (int i = head[x]; i ; i = e[i].next) {
                int v = e[i].node;
                if (dis[v] > dis[x] + e[i].value) {
                    dis[v] = dis[x] + e[i].value;
                    que.push(make_pair(dis[v],v));
                }
            }
        }
    }
}

inline int read() {
    int num = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == -) f = -1;
        ch = getchar(); 
    }
    while (isdigit(ch)) {
        num = num * 10 + ch - 0;
        ch = getchar();
    }
    return num * f;
}

int main() {
    n = read(); m = read(); s = read();
    for (int i = 1; i <= m; i++) {
        int x,y,z;
        x = read(); y = read(); z = read();
        add(x,y,z);
    }
    for (int i = 1; i <= n; i++) dis[i] = oo;
    dijkstra(s);
    for (int i = 1; i <= n; i++)
        printf("%d ",dis[i]);
    return 0;
} 

 

ddd

Dijkstra

标签:tor   tchar   stream   namespace   ring   temp   air   return   head   

原文地址:https://www.cnblogs.com/hkttg/p/8360737.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!