Cod sursa(job #2410036)

Utilizator LucaSeriSeritan Luca LucaSeri Data 19 aprilie 2019 17:43:21
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <bits/stdc++.h>

using namespace std;

const int inf = 1e9;

class cmp {
	public:
		const bool operator () (const pair< int, int > &a, const pair< int, int > &b) const {
			return a.second > b.second;
		}
};

int main() {
	#ifdef BLAT
		freopen("input", "r", stdin);
	#else
		freopen("dijkstra.in", "r", stdin);
		freopen("dijkstra.out", "w", stdout);
	#endif

	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int n;
	cin >> n;

	vector< vector< pair< int, int > > > gr(n + 1);

	int m;
	cin >> m;

	for(int i = 0; i < m; ++i) {
		int a, b, c;
		cin >> a >> b >> c;
		gr[a].emplace_back(b, c);
	}

	vector< int > dist(n + 1, inf);
	dist[1] = 0;
	priority_queue< pair< int, int >, vector< pair< int, int > >, cmp > h;

	h.push({1, 0});
	while(h.size()) {
		int node, cost;
		tie(node, cost) = h.top();
		h.pop();
		if(cost != dist[node]) continue;

		for(auto &x : gr[node]) {
			if(cost + x.second < dist[x.first]) {
				dist[x.first] = cost + x.second;
				h.push({x.first, dist[x.first]});
			}
		}
	}

	for(int i = 2; i <= n; ++i) {
		cout << (dist[i] == inf ? 0 : dist[i]) << ' ';
	}
	return 0;
}