Cod sursa(job #2931625)

Utilizator matthriscuMatt . matthriscu Data 31 octombrie 2022 17:29:24
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h>
using namespace std;

#define INF 1e9

class graph {
	vector<vector<pair<uint, int>>> adj;
	uint nodes;

public:
	graph(uint nodes) : adj(nodes), nodes(nodes) {}

	void add_edge(uint x, uint y, int c) {
		adj[x].push_back({y, c});
	}

	vector<uint> dijkstra(uint src) {
		vector<uint> dist(nodes, INF);
		vector<bool> visited(nodes, false);

		priority_queue<pair<uint, uint>> pq;
		pq.push({0, src});
		dist[src] = 0;
		
		while (!pq.empty()) {
			auto [current_dist, current] = pq.top();
			pq.pop();

			if (visited[current])
				continue;

			visited[current] = true;

			for (const auto& [neigh, cost] : adj[current])
				if (dist[current] + cost < dist[neigh]) {
					dist[neigh] = dist[current] + cost;
					pq.push({-dist[current] - cost, neigh});
				}
		}

		return dist;
	}
};

int main() {
	ifstream fin("dijkstra.in");
	ofstream fout("dijkstra.out");
	
	uint n, m;
	fin >> n >> m;

	graph g(n);
	for (uint i = 0, x, y, c; i < m; ++i) {
		fin >> x >> y >> c;
		g.add_edge(x - 1, y - 1, c);
	}

	vector<uint> ans = g.dijkstra(0);

	for (uint i = 1; i < n; ++i)
		fout << (ans[i] == INF ? 0 : ans[i]) << ' ';
}