Cod sursa(job #1687139)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 12 aprilie 2016 18:13:04
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>

#define pii pair < int , int >

using namespace std;

const int nmax = 5e4 + 10;
const int inf = 0x3f3f3f3f;

int n , m , i;
int cost[nmax] , used[nmax];
vector < pii > g[nmax];

priority_queue < pii , vector < pii > , greater < pii > > pq;

void bagadijkstra()
{
    memset(cost , inf , sizeof(cost));

    int node = 1; cost[node] = 0;
    pq.push({cost[node] , node});

    while (pq.size())
    {
        node = pq.top().second; pq.pop();
        if (used[node]) continue;

        for (auto &it : g[node])
        {
            if (cost[it.first] <= cost[node] + it.second) continue;
            cost[it.first] = cost[node] + it.second;
            pq.push({cost[it.first],it.first});
        }
        used[node] = 1;
    }
}

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

    scanf("%d %d", &n, &m);
    for (i = 1; i <= m; ++i)
    {
        int x , y , z;
        scanf("%d %d %d", &x, &y, &z);

        g[x].push_back({y,z});
        g[y].push_back({x,z});
    }

    bagadijkstra();

    for (i = 2; i <= n; ++i)
        printf("%d ", cost[i]);

    return 0;
}