Cod sursa(job #2047454)

Utilizator Alex18maiAlex Enache Alex18mai Data 24 octombrie 2017 21:02:55
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream cin ("dijkstra.in");
ofstream cout ("dijkstra.out");

struct node{
    int next , val;
};

class cmp{
public:
    bool operator() (node a , node b){
        return a.val > b.val;
    }
};

priority_queue<node , vector<node> , cmp> Q;
int dp[50100];
vector < vector <node> > gr(50100);

int main() {

    int n , m;
    cin>>n>>m;

    for (int i=2; i<=n; i++){
        dp[i] = 1000000000;
    }

    for (int i=1; i<=m; i++){
        int a , b , val;
        cin>>a>>b>>val;

        node now;
        now.next = b;
        now.val = val;

        gr[a].push_back(now);

        now.next = a;

        gr[b].push_back(now);
    }

    node now;
    now.next = 1;
    now.val = 0;

    Q.push(now);

    while (!Q.empty()){
        node now = Q.top();
        Q.pop();
        for (auto &x : gr[now.next]){
            if (dp[x.next] > dp[now.next] + x.val){
                dp[x.next] = dp[now.next] + x.val;
                Q.push(x);
            }
        }
    }

    for (int i=2; i<=n; i++){
        if (dp[i] == 1000000000){
            cout<<0<<" ";
        }
        else{
            cout<<dp[i]<<" ";
        }
    }

    return 0;
}