Cod sursa(job #1889038)

Utilizator theodor1289Theodor Amariucai theodor1289 Data 22 februarie 2017 15:20:11
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <set>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int NMAX = 50005;
const int INF = 1e10;

vector< pair<int, int> > G[NMAX];
vector< pair<int, int> >::iterator it;
set<int> h;

int dist[NMAX], node, to, cost, d;

int main() {

    int n, m;
    fin >> n >> m;

    for (int i = 0; i < m; ++i) {
        int from, to, cost;
        fin >> from >> to >> cost;
        G[from].push_back(make_pair(to, cost));
    }

    for(int i=1;i<=n;i++)
        dist[i]=INF;
    dist[1] = 0;

    h.insert(1);
    while(!h.empty())
    {
        node=*h.begin();
        h.erase(h.begin());

        for(it=G[node].begin(); it!=G[node].end(); it++)
        {
            to=it->first;
            cost=it->second;

            if(dist[node] + cost < dist[to])
            {
                //if(dist[to]!=INF)
                //    h.erase(h.find(to));

                dist[to] = dist[node] + cost;
                h.insert(to);
            }
        }
    }

    for (int i = 2; i <= n; ++i)
        {
        if (dist[i] == INF)
            dist[i] = 0;

        fout << dist[i] << ' ';
        }
    fout << '\n';
}