Cod sursa(job #1593678)

Utilizator Theodor1000Cristea Theodor Stefan Theodor1000 Data 8 februarie 2016 19:54:15
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <cstdio>
#include <algorithm>
#include <queue>
#include <functional>
#include <tuple>

#define f first
#define s second

using namespace std;

priority_queue < pair <int, int>, vector < pair <int, int> >, greater < pair <int, int> > > q;
vector < pair <int, int> > v[50010];
int rez[50010];
bool ap[50010];

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

    int n, m;
    scanf ("%d %d", &n, &m);

    for (int i = 1; i <= m; ++i)
    {
        int a, b, c;
        scanf ("%d %d %d", &a, &b, &c);

        v[a].emplace_back (b, c);
        v[b].emplace_back (a, c);
    }

    for (int i = 2; i <= n; ++i)
        rez[i] = 2000000000;

    q.emplace (0, 1);
    while (!q.empty ())
    {
        int cost, poz;
        tie (cost, poz) = q.top ();
        q.pop ();

        if (ap[poz]) continue;
        ap[poz] = true;

        for (int i = 0; i < v[poz].size (); ++i)
            if (rez[v[poz][i].f] > v[poz][i].s + cost && !ap[v[poz][i].f])
            {
                rez[v[poz][i].f] = v[poz][i].s + cost;
                q.emplace (rez[v[poz][i].f], v[poz][i].f);
            }
    }

    for (int i = 2; i <= n; ++i)
        if (rez[i] == 2000000000) printf ("0 ");
        else printf ("%d ", rez[i]);

    printf ("\n");

    return 0;
}