Cod sursa(job #2207417)

Utilizator Marius7122FMI Ciltea Marian Marius7122 Data 25 mai 2018 17:46:21
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

const int N = 50005;
const int inf = 1 << 30;

struct lat
{
    int y, l;
};

vector<lat> g[N];
int n, m;
int viz[N], d[N];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int,int>>> pq;

int main()
{
    ifstream fin("dijkstra.in");
    ofstream fout("dijkstra.out");

    ///citire
    fin>>n>>m;
    while(m--)
    {
        int x,y,l;
        fin>>x>>y>>l;
        g[x].push_back({y,l});
    }

    ///initializare
    for(int i=2;i<=n;i++)
        d[i] = inf;


    ///dijkstra
    pq.push({0, 1});
    while(!pq.empty())
    {
        int x = pq.top().second;
        pq.pop();
        viz[x]++;

        if(viz[x] > 1)
            continue;

        for(auto y : g[x])
            if(!viz[y.y] && d[y.y] > d[x] + y.l)
            {
                d[y.y] = d[x] + y.l;
                pq.push({d[y.y], y.y});
            }
    }

    ///afisare
    for(int i=2;i<=n;i++)
    {
        if(d[i] == inf)
            d[i] = 0;
        fout<<d[i]<<' ';
    }


    return 0;
}