zoukankan      html  css  js  c++  java
  • Dijkstra

    #include <bits/stdc++.h>
    #define N 200001
    #define M 500001
    #define pr pair<int,int>
    #define mk make_pair
    
    using namespace std;
    
    const int INF = 0x7fffffff;
    
    struct Node{
        int v,val,nxt;
    }e[M];
    
    int n,m,s,top;
    int dist[N],head[N];
    
    void add(int u,int v,int w){
        ++top;
        e[top].v = v;
        e[top].val = w;
        e[top].nxt = head[u];
        head[u] = top;
    }
    
    priority_queue<pr,vector<pr>,greater<pr> > q;
    void Dijkstra(){
        for(int i = 1; i <= n; ++i) dist[i] = INF;
        dist[s] = 0;
        q.push(mk(0, s));
        while(!q.empty()){
            int u = q.top().second;
            int d = q.top().first;
            q.pop();
            if(dist[u] < d) continue;
            for(int i = head[u]; i; i = e[i].nxt){
                if(dist[e[i].v] > d + e[i].val){
                    dist[e[i].v] = d + e[i].val;
                    q.push(mk(dist[e[i].v], e[i].v));
                }
            }
        }
        for(int i = 1; i <= n; ++i) cout << dist[i] << " ";
        //cout << dist[n];
    }
    
    int main(){
        cin >> n >> m >> s;
        for(int i = 1, u, v, w; i <= m; ++i){
            cin >> u >> v >> w;
            add(u, v, w);
        }
        Dijkstra();
        return 0;
    }
  • 相关阅读:
    90. 子集 II 回溯算法
    47. 全排列 II 回溯算法
    40. 组合总和 II
    39. 组合总和 回溯
    NLP 第八课 语言技术-文本与LDA主题模型
    36. 有效的数独
    31. 下一个排列
    HDU 4527
    HDU 4521
    HDU 5191
  • 原文地址:https://www.cnblogs.com/Adventurer-H/p/10884486.html
Copyright © 2011-2022 走看看