Cod sursa(job #1923098)

Utilizator preda.andreiPreda Andrei preda.andrei Data 10 martie 2017 20:43:48
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <forward_list>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

using Pair = pair<int, int>;

struct Node
{
	int cost;
	forward_list<Pair> edges;
};

using Graph = vector<Node>;

const int kInf = (1 << 30);

void FindCosts(Graph &g, int start)
{
	for (auto &node : g) {
		node.cost = kInf;
	}
	g[start].cost = 0;

	priority_queue<Pair, vector<Pair>, greater<Pair>> q;
	q.push({0, start});

	while (!q.empty()) {
		int node = q.top().second;
		int cost = q.top().first;
		q.pop();

		if (cost != g[node].cost) {
			continue;
		}

		for (const auto &edge : g[node].edges) {
			int next = edge.first;
			int new_cost = cost + edge.second;
			if (new_cost < g[next].cost) {
				g[next].cost = new_cost;
				q.push({new_cost, next});
			}
		}
	}
}

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

	int n, m;
	fin >> n >> m;

	Graph graph(n);
	while (m--) {
		int x, y, c;
		fin >> x >> y >> c;
		graph[x - 1].edges.push_front({y - 1, c});
	}

	FindCosts(graph, 0);
	for (int i = 1; i < n; ++i) {
		if (graph[i].cost == kInf) {
			fout << 0 << " ";
		} else {
			fout << graph[i].cost << " ";
		}
	}
	fout << "\n";

	return 0;
}