Cod sursa(job #2869109)

Utilizator alextmAlexandru Toma alextm Data 11 martie 2022 12:36:01
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>
using namespace std;

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

typedef pair<int,int> PII;
const int MAXN = 50005;
const int INF = 1e9;

priority_queue<PII, vector<PII>, greater<PII>> Q;
vector<PII> G[MAXN];
int n, dp[MAXN];

void Dijkstra() {
	for(int i = 2; i <= n; i++)
		dp[i] = INF;

	dp[1] = 0;
	Q.push({0, 1});

	while(!Q.empty()) {
		int node = Q.top().second;
		int dist = Q.top().first;
		Q.pop();

		if(dist > dp[node]) continue;
		for(auto son : G[node])
		if(dp[node] + son.second < dp[son.first]) {
			dp[son.first] = dp[node] + son.second;
			Q.push({dp[son.first], son.first});
		}
	}
}

int main() {
	int m, u, v, cost;
	fin >> n >> m;

	while(m--) {
		fin >> u >> v >> cost;
		G[u].emplace_back(v, cost);
	}

	Dijkstra();

	for(int i = 2; i <= n; i++)
		fout << (dp[i] == INF ? 0 : dp[i]) << ' ';
	fout << '\n';

	return 0;
}