Cod sursa(job #2535323)

Utilizator stefan.popescuPopescu Stefan stefan.popescu Data 31 ianuarie 2020 19:11:22
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define VPII vector < pair <int, int> >::iterator
using namespace std;
const int oo=2000000000;
ifstream in ("dijkstra.in");
ofstream out("dijkstra.out");
priority_queue < pair <int, int>, vector <pair<int, int> >, greater<pair<int, int> > > q;
vector < vector <pair <int, int> > > a;
int n, m, x, y, c;
int cost[50010];
int main()
{
    ios_base::sync_with_stdio(false);
    in.tie(0);
    out.tie(0);
    in>>n>>m;
    a.resize(n+1);
    for(int i=1; i<=m; i++)
    {
        in>>x>>y>>c;
        a[x].push_back({y, c});
    }
    for(int i=2; i<=n; i++)
        cost[i]=oo;
    q.push({0, 1});
    while(!q.empty())
    {
        c=q.top().first;
        x=q.top().second;
        q.pop();
        if(c>cost[x]) continue;
        for(VPII it=a[x].begin(); it!=a[x].end(); ++it)
        {
            if(c+it->second<cost[it->first])
            {
                cost[it->first]=c+it->second;
                q.push({cost[it->first], it->first});
            }
        }
    }
    for(int i=2; i<=n; i++)
        out<<((cost[i]==oo) ? 0 : cost[i])<<" ";
    return 0;
}