Cod sursa(job #2848206)

Utilizator george_buzasGeorge Buzas george_buzas Data 12 februarie 2022 11:11:27
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#include <bitset>
#define INF 0x7f7f7f7f
using namespace std;

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

typedef pair<int, int> pair_def;
vector<pair_def> weighted_graph[50001];
priority_queue<pair_def> neighbors;
int distances[50001], nr_nodes, nr_edges;
bitset<50001> is_visited;

void dijkstra_traversal() {
	memset(distances, INF, sizeof distances);
	distances[1] = 0;
	neighbors.push({ 0, 1 });
	is_visited[1] = true;
	while (!neighbors.empty()) {
		int current_node = neighbors.top().second;
		int current_nr_neighbors = weighted_graph[current_node].size();
		neighbors.pop();
		for (int i = 0; i < current_nr_neighbors; ++i) {
			int neighbor = weighted_graph[current_node][i].first;
			int cost = weighted_graph[current_node][i].second;
			if (is_visited[neighbor] == false) {
				if (distances[neighbor] > distances[current_node] + cost) {
					distances[neighbor] = distances[current_node] + cost;
					neighbors.push({ -distances[neighbor], neighbor });
					is_visited[neighbor] = true;
				}
			}
		}
	}
}

void print_optimal_distance() {
	for (int i = 2; i <= nr_nodes; ++i) {
		if (distances[i] == INF) {
			fout << 0 << ' ';
		} else {
			fout << distances[i] << ' ';
		}
	}
}

int main() {
	fin >> nr_nodes >> nr_edges;
	int src_node, dest_node, edge_cost;
	for (int edge = 1; edge <= nr_edges; ++edge) {
		fin >> src_node >> dest_node >> edge_cost;
		weighted_graph[src_node].push_back({ dest_node, edge_cost });
	}
	dijkstra_traversal();
	print_optimal_distance();
	return 0;
}