Cod sursa(job #2354484)

Utilizator AndreiLunguLungu Andrei Sebastian AndreiLungu Data 25 februarie 2019 12:39:19
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
#define Nmax 50004
#define Mmax 250004
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n , d[Nmax] , viz[Nmax] , m;
///            nodul,cost
vector < pair <int, int> > L[Nmax];
///                     cost, nod
priority_queue < pair < int , int > >Q;
const int oo = 1e9;
void Citire()
{
    int i , x , y , c;
    fin >> n >> m;
    for(i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;
        L[x].push_back({y , c});
        L[y].push_back({x , c});
    }
    fin.close();
}
void Dijkstra()
{
    int i , j , k , c;
    ///pun infinit in d[]
    for(i = 1; i <= n; i++)
        d[i] = oo;
    d[1] = 0;
    Q.push({0, 1});
    viz[1] = 1;
    for(i = 1; i <= m; i++)
    {
        k = Q.top().second;
        viz[k] = 0;
        Q.pop();
        ///caut adiacentii lui k
        for(auto w : L[k])
        {
            j = w.first;///nodul adiacent
            c = w.second;///costul nodului adiacent
            if(d[j] > d[k] + c)
            {
                d[j] = d[k] + c;
                if(viz[j] == 0)
                {
                    viz[j] = 1;
                    Q.push({-d[j], j});
                }
            }
        }
    }
    for(i = 2; i <= n; i++)
        fout << d[i] << " ";
}
int main()
{
    Citire();
    Dijkstra();
    return 0;
}