Cod sursa(job #1790705)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 28 octombrie 2016 17:15:47
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;
vector<vector<pair<int,int> > > G;
priority_queue<pair<int,int> > Q;
const int Nmax = 666013,
          INF = 0x3f3f3f3f;
int N, M, dp[Nmax];



void readGraph()
{
    cin.sync_with_stdio(false);
    cin >> N >> M;
    G.resize(N + 1);
    for(int i = 1; i <= M; ++i) {
        int a, b, c;
        cin >> a >> b >> c;
        G[a].emplace_back(c,b);
    }
}

void dijkstra(int k)
{
    Q.push({0,k});
    memset(dp, INF, sizeof(dp));
    dp[k] = 0;

    while(!Q.empty())
    {
        auto crt = Q.top(); Q.pop();
        int cost = - crt.first;
        int node = crt.second;

        ///if(cost != dp[node])
           /// continue;

        for(auto it : G[node])
            if(dp[it.second] > dp[node] + it.first) {
                dp[it.second] = dp[node] + it.first;
                Q.push({-dp[it.second],it.second});
            }
    }
}

int main()
{
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);

    readGraph();
    dijkstra(1);

    for(int i = 2; i <= N; ++i)
        if(dp[i] >= INF)
            cout << "0 ";
        else
            cout << dp[i] << " ";


    return 0;
}