Cod sursa(job #2887749)

Utilizator CyborgSquirrelJardan Andrei CyborgSquirrel Data 10 aprilie 2022 09:57:06
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

struct Edge {
	int b, v;
};

struct Node {
	int a, v;
};
bool operator<(const Node &lhs, const Node &rhs) {
	return lhs.v > rhs.v;
}

const int INF = 0x3f3f3f3f;
const int N = 50041;

int n, m;
vector<Edge> gra[N];
int d[N];

int main() {
	fin >> n >> m;
	for (int i = 0; i < m; ++i) {
		int a, b, v;
		fin >> a >> b >> v;
		gra[a].push_back({b, v});
	}
	
	for (int i = 1; i <= n; ++i) {
		d[i] = INF;
	}
	
	priority_queue<Node> pq;
	d[1] = 0;
	pq.push({1, 0});
	while (!pq.empty()) {
		auto node = pq.top(); pq.pop();
		if (node.v < d[node.a]) continue;
		for (auto edge : gra[node.a]) {
			if (d[node.a] + edge.v < d[edge.b]) {
				d[edge.b] = d[node.a] + edge.v;
				pq.push({edge.b, d[node.a] + edge.v});
			}
		}
	}
	
	for (int i = 2; i <= n; ++i) {
		fout << ((d[i] < INF) ? d[i] : 0) << " ";
	}
	
	return 0;
}