Cod sursa(job #2170383)

Utilizator jeanFMI - Petcu Ion Cristian jean Data 15 martie 2018 00:04:09
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#define NMAX 50010
using namespace std;

typedef pair<int, int> int_pair;

vector<int_pair> G[NMAX];
int dist[NMAX];
bool used[NMAX];
priority_queue<int_pair, vector<int_pair>, greater<int_pair> > heap;
    
void dijkstra(int N, int start) {
    memset(dist, -1, sizeof(dist));
    dist[start] = 0;
    heap.push(make_pair(0, start));

    int_pair p;
    while (N) {
        p = heap.top();
        heap.pop();
        if (used[p.second]) continue;
        used[p.second] = true;
        N--;
        
        for (auto &edge : G[p.second]) {
            if (dist[edge.first] == - 1 || dist[edge.first] > dist[p.second] + edge.second) {
                dist[edge.first] = dist[p.second] + edge.second;
                heap.push(make_pair(dist[edge.first], edge.first));
            }  
        }
    }
}

int main() {
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
 
    int N, M, x, y, c, i;
    cin >> N >> M;
    for (i = 0; i < M; i++) {
        cin >> x >> y >> c;
        G[x].push_back(make_pair(y, c));
    }

    dijkstra(N, 1);
    for (i = 2; i <= N; i++) {
        cout << ((dist[i] == -1) ? 0 : dist[i]) << ' ';
    }
 
    return 0;
}