Cod sursa(job #3373671)

Utilizator mihalachecostin.danielMihalache Costin-Daniel mihalachecostin.daniel Data 7 noiembrie 2026 15:31:38
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
using namespace std;

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

const int N = 50005;
const long long INF = 1e18;
vector<pair<int, int>> g[N];      // g[u] = {v, cost}
long long d[N]; int p[N];
void dijkstra(int s, int n) {
	for (int i = 1;i <= n;i++) d[i] = INF, p[i] = 0;
	priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;
	d[s] = 0; pq.push({ 0,s });
	while (!pq.empty()) {
		pair<long long, int> t = pq.top(); pq.pop();
		long long c = t.first; int u = t.second;
		if (c > d[u]) continue;        
		for (size_t k = 0;k < g[u].size();k++) {
			int v = g[u][k].first, w = g[u][k].second;
			if (d[u] + w < d[v]) { d[v] = d[u] + w; p[v] = u; pq.push({ d[v],v }); }
		}
	}
}

int main()
{
	int n, m;
	fin >> n >> m;
	for (int i = 0; i < m; i++) {
		int a, b, c;
		fin >> a >> b >> c;
		g[a].push_back({ b, c });       // orientat; pentru neorientat adaugă și g[b].push_back({a,c});
	}
	dijkstra(1, n);
	for (int i = 2; i <= n; i++)
		fout << (d[i] == INF ? 0 : d[i]) << " ";
}