Cod sursa(job #1928942)

Utilizator andru47Stefanescu Andru andru47 Data 16 martie 2017 21:48:37
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>
#define per pair<int , int>
#define f first
#define s second
using namespace std;
const int NMAX = 50005;
int ans[NMAX] , n , m;
vector <per> g[NMAX];
priority_queue <per , vector <per> , greater<per> > pq;
inline void dijkstra()
{
    pq.push({0 , 1});
    for (int i = 1; i<=n; ans[i] = INT_MAX , ++i);
    ans[1] = 0;
    while(!pq.empty())
    {
        per X = pq.top();
        pq.pop();
        if (X.f != ans[X.s])continue;
        for (auto &it : g[X.s])
        {
            if (ans[it.f] <= X.f + it.s)continue;
            ans[it.f] = X.f + it.s;
            pq.push({ans[it.f] , it.f});
        }
    }
}
int main()
{
    freopen("dijkstra.in" , "r", stdin);
    freopen("dijkstra.out" , "w", stdout);

    scanf("%d %d\n", &n, &m);
    for (int i = 1; i<=m; ++i)
    {
        int x , y, cost;
        scanf("%d %d %d\n", &x, &y, &cost);
        g[x].push_back({y , cost});
    }
    dijkstra();
    for (int i = 2; i<=n; ++i)
        printf("%d ", ans[i] == INT_MAX ? 0 : ans[i]);
    return 0;
}