Cod sursa(job #1881285)

Utilizator razvan99hHorhat Razvan razvan99h Data 16 februarie 2017 12:39:29
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define DM 50005
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int INF = (1 << 31) - 1; //MAX INT
int n, m, i, j, a, b, c, nod, dist[DM];
priority_queue < pair<int, int> > pq;
vector < pair<int, int> > g[DM];
bool viz[DM];


void dijkstra()
{
    dist[1] = 0;
    for(int i = 2; i <= n; i++)
        dist[i] = INF;
    pq.push(make_pair(0, 1)); // aici la pq first e distanta, second e nodul

    while(!pq.empty())
    {
        nod = pq.top().second;
        pq.pop();

        if(!viz[nod])
        {
            viz[nod] = 1;
            for(auto it:g[nod])
            {
                if( dist[nod] + it.second < dist[it.first])
                {
                    dist[it.first] = dist[nod] + it.second;
                    pq.push(make_pair(-dist[it.first], it.first));
                }
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> a >> b >> c;
        g[a].push_back(make_pair(b, c)); // aici la graf first e valoarea(nodul), second e distanta
    }
    dijkstra();
    for(int i = 2; i <= n; i++)
    {
        if(dist[i] == INF)
            dist[i] = 0;
        fout << dist[i] << ' ';
    }
    return 0;
}