Cod sursa(job #2189791)

Utilizator MystyQueNimeni Altu MystyQue Data 28 martie 2018 23:43:10
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
const int nmax = 50005;
const int inf = 1 << 30;
bool InQ[nmax];
int D[nmax];
vector < pair<int,int> > A[nmax];
struct str { bool operator()(int x, int y) {return D[x]>D[y];}};
priority_queue <int, vector <int>, str > Q;
int n, x, y, z, m;
void Dijkstra(int x)
{
    for(int i = 2; i <= n; ++ i) D[i] = inf;
    Q.push(x); InQ[x] = 1;
    while(!Q.empty())
    {
        x = Q.top();
        InQ[x] = false;
        Q.pop();
        for(auto i:A[x])
            if(D[i.first] > D[x] + i.second)
            {
                D[i.first] = D[x] + i.second;
                if(!InQ[i.first]) Q.push(i.first), InQ[i.first] = 1;
            }
    }
}
int main()
{
    cin >> n >> m;
    for(int i = 1; i <= m; ++ i) cin >> x >> y >> z, A[x].push_back({y,z});
    Dijkstra(1);
    for(int i = 2; i <= n; ++ i)
        if(D[i] == inf) cout << "0 ";
        else cout << D[i] << ' ';

}