Cod sursa(job #2532079)

Utilizator radustn92Radu Stancu radustn92 Data 27 ianuarie 2020 12:17:37
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

struct edge {
	int to, cost;
};
const int NMAX = 50505;
const int INF = 0x3f3f3f3f;

int N, M;
vector<edge> G[NMAX];

void read() {
	scanf("%d%d", &N, &M);
	int x, y, cost;
	for (int edgeIdx = 0; edgeIdx < M; edgeIdx++) {
		scanf("%d%d%d", &x, &y, &cost);
		G[x].push_back({y, cost});
	}
}

void solve() {
	vector<int> D(N + 1, INF);
	vector<bool> use(N + 1, false);
	D[1] = 0;
	for (int step = 1; step <= N; step++) {
		int bestNode = -1;
		for (int node = 1; node <= N; node++) {
			if (!use[node] && (bestNode == -1 || D[bestNode] > D[node])) {
				bestNode = node;
			}
		}

		use[bestNode] = true;
		for (auto& outgoingEdge : G[bestNode]) {
			D[outgoingEdge.to] = min(D[outgoingEdge.to], D[bestNode] + outgoingEdge.cost);
		}
	}

	for (int node = 2; node <= N; node++) {
		if (D[node] == INF) {
			printf("0 ");
		} else {
			printf("%d ", D[node]);
		}
	}
	printf("\n");
}

int main() {
	freopen("dijkstra.in", "r", stdin);
	freopen("dijkstra.out", "w", stdout);

	read();
	solve();
	return 0;
}