Cod sursa(job #2639244)

Utilizator ZahaZaharie Stefan Zaha Data 1 august 2020 09:23:51
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#define ll long long
using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
vector<pair<int, int>> graph[50005];
ll dist[50005]; // distance

struct minDist {
	bool operator()(int x, int y) {
		return dist[x] > dist[y];
	}
};
priority_queue<int, vector<int>, minDist> toVisit;
bitset<50005> queued;

void calcDist() {
	while (!toVisit.empty()) {
		int node = toVisit.top();
		toVisit.pop();
		queued[node] = false;

		for (unsigned i = 0; i < graph[node].size(); ++i) {
			int next = graph[node][i].first, weight = graph[node][i].second;
			if (dist[next] > dist[node] + weight) {
				dist[next] = dist[node] + weight;
				if (!queued[next]) {
					toVisit.emplace(next);
					queued[next] = true;
				}
			}
		}
	}
}

int main() {
	int n, m;
	fin >> n >> m;
	while (m--) {
		int x, y, w;
		fin >> x >> y >> w;
		graph[x].emplace_back(make_pair(y, w));
	}

	for (int i = 2; i <= n; ++i)
		dist[i] = 5000000005;
	toVisit.emplace(1);
	queued[1] = true;
	calcDist();

	for (int i = 2; i <= n; ++i) {
		if (dist[i] != 5000000005)
			fout << dist[i] << " ";
		else
			fout << "0 ";
	}
	return 0;
}