Cod sursa(job #2947528)

Utilizator andrei_C1Andrei Chertes andrei_C1 Data 26 noiembrie 2022 11:30:01
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>
// #include <ext/pb_ds/priority_queue.hpp>

using namespace std;

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

const int NMAX = 5e4;
const int INF = 0x3f3f3f3f;

int N, M;
vector<pair<int, int>> adj[NMAX + 1];

int dist[NMAX + 1];
// __gnu_pbds :: priority_queue<pair<int, int>, greater<pair<int, int>>, __gnu_pbds :: pairing_heap_tag> pq;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

void dij(int u = 1) {
	memset(dist, INF, sizeof(dist));
	dist[u] = 0;
	pq.push({dist[u], u});

	while(!pq.empty()) {
		int v = pq.top().second, cst = pq.top().first;
		pq.pop();

		if(cst != dist[v]) {
			continue;
		}

		for(const auto &it: adj[v]) {
			if(dist[it.first] > cst + it.second) {
				dist[it.first] = cst + it.second;
				pq.push({dist[it.first], it.first});
			}
		}
	}
}

int main() {
	ios_base :: sync_with_stdio(false);

	fin >> N >> M;

	for(int i = 1; i <= M; i++) {
		int u, v, c;
		fin >> u >> v >> c;

		adj[u].push_back({v, c});
	}

	dij();

	for(int i = 2; i <= N; i++) {
		if(dist[i] == INF) {
			dist[i] = 0;
		}
		fout << dist[i] << " ";
	}
	fout << '\n';

	fin.close();
	fout.close();
	return 0;
}