Cod sursa(job #1891506)

Utilizator theodor1289Theodor Amariucai theodor1289 Data 24 februarie 2017 08:43:44
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <set>
#include <queue>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
 
const int NMAX = 50005;
const int INF = 1e10;

typedef pair<int,int> Pair;
vector<Pair> G[NMAX];
vector<Pair>::iterator it;
priority_queue<Pair, vector<Pair>, greater<Pair> > 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.push(make_pair(0, 1));
    while(!h.empty())
    {
        node=h.top().second;
        h.pop();
 
        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(make_pair(dist[to], to)));
 
                dist[to] = dist[node] + cost;
                h.push(make_pair(dist[to], to));
            }
        }
    }
 
    for (int i = 2; i <= n; ++i)
        {
        if (dist[i] == INF)
            dist[i] = 0;
 
        fout << dist[i] << ' ';
        }
    fout << '\n';
}