Cod sursa(job #838252)

Utilizator sebii_cSebastian Claici sebii_c Data 19 decembrie 2012 10:32:37
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <cstdio>
#include <cstring>

#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

const int MAXN = 50100;
const int INF = (int)(1e9 + 7);

int n, m;
int d[MAXN];
vector<pair<int, int> > heap;
vector<int> G[MAXN], C[MAXN];

void dijkstra()
{
    for (int i = 2; i <= n; ++i) 
        d[i] = INF;
    heap.push_back(make_pair(0, 1));
    make_heap(heap.begin(), heap.end());
    while (!heap.empty()) {
        int val = heap.front().first;
        int x = heap.front().second;
        pop_heap(heap.begin(), heap.end());
        heap.pop_back();
        for (int i = 0; i < G[x].size(); ++i)
            if (d[G[x][i]] > val + C[x][i]) {
                d[G[x][i]] = val + C[x][i];
                heap.push_back(make_pair(d[G[x][i]], G[x][i]));
                push_heap(heap.begin(), heap.end());
            }
    }
}

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

    cin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int a, b, c;
        cin >> a >> b >> c;
        G[a].push_back(b);
        C[a].push_back(c);
    }
    dijkstra();

    for (int i = 2; i <= n; ++i)
        if (d[i] >= INF) cout << 0 << " ";
        else cout << d[i] << " ";
    cout << "\n";

    return 0;
}