Cod sursa(job #2819207)

Utilizator alextmAlexandru Toma alextm Data 18 decembrie 2021 09:25:50
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>
using namespace std;

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

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

priority_queue<PII, vector<PII>, greater<PII>> PQ;
vector<PII> G[MAXN];
int n, d[MAXN];

void Dijkstra(int start) {
	for(int i = 1; i <= n; i++)
		d[i] = INF;
	
	d[start] = 0;
	PQ.push({0, start});
	
	while(!PQ.empty()) {
		int dist = PQ.top().first;
		int node = PQ.top().second;
		PQ.pop();
		
		if(dist > d[node])
			continue;
			
		for(auto nxt : G[node])
			if(d[node] + nxt.second < d[nxt.first]) {
				d[nxt.first] = d[node] + nxt.second;
				PQ.push({d[nxt.first], nxt.first});
			}
	}
}

int main() {
	int m, a, b, c;
	
	fin >> n >> m;
	while(m--) {
		cin >> a >> b >> c;
		G[a].emplace_back(b, c);
		G[b].emplace_back(a, c);
	}
	
	Dijkstra(1);
	
	for(int i = 2; i <= n; i++)
		fout << d[i] << " ";
	fout << "\n";
	
	return 0;
}