Cod sursa(job #2843232)

Utilizator game_difficultyCalin Crangus game_difficulty Data 2 februarie 2022 11:03:48
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");

vector<pair<int, int>> graf[50005];
int dist[50005];
bool visited[50005];

int main() {
	int n, m;
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int x, y, d;
		cin >> x >> y >> d;
		graf[x].push_back({ y, d });
	}
	priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
	q.push({ 0, 1 });
	while (!q.empty()) {
		int now = q.top().second;
		q.pop();
		if (visited[now] == true) continue;
		visited[now] = true;
		for (auto i : graf[now]) {
			if (!visited[i.first]) {
				if (dist[now] + i.second < dist[i.first] || dist[i.first] == 0) {
					dist[i.first] = dist[now] + i.second;
					q.push({ dist[i.first], i.first });
				}
			}
		}
	}
	for (int i = 2; i <= n; i++) {
		cout << dist[i] << ' ';
	}
	return 0;
}