Cod sursa(job #2271664)

Utilizator marcudanfDaniel Marcu marcudanf Data 29 octombrie 2018 03:22:30
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <set>

const int INF = 1<<29;
const int NMAX = 5e4  + 5;

using namespace std;

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

vector < pair < int, int > > g[NMAX];
set < pair <int, int > > heap;

int d[NMAX];

int n, m;

int main(){
	fin >> n >> m;
	while(m--){
		int a, b, c;
		fin >> a >> b >> c;
		g[a].push_back({b, c});
	}
	for(int i = 2; i <= n; i++)
		d[i] = INF;
	heap.insert({0, 1});
	while(!heap.empty()){
		auto h = *heap.begin();
		int nod = h.second;
		heap.erase(heap.begin());
		for(auto i : g[nod]){
			if(d[i.first] > d[nod] + i.second){
				if(d[i.first] != INF)
					heap.erase(heap.find({d[i.first], i.first}));
				d[i.first] = d[nod] + i.second;
				heap.insert({d[i.first], i.first});
			}
		}
	}
	for(int i = 2; i <= n; i++)
		if(d[i] == INF)
			fout << "0 ";
		else
			fout << d[i] << ' ';
	return 0;
}