Cod sursa(job #2895926)

Utilizator matthriscuMatt . matthriscu Data 29 aprilie 2022 16:54:05
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <bits/stdc++.h>
using namespace std;

#define NMAX 50005
#define INF 0x7F7F7F7F

int dist[NMAX];

struct cmp {
	bool operator()(int x, int y) {
		return dist[x] > dist[y];
	}
};

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

	int n, m;
	scanf("%d%d", &n, &m);

	vector<pair<int, int>> G[NMAX];
	for (int i = 1, x, y, c; i <= m; ++i) {
		scanf("%d%d%d", &x, &y, &c);
		G[x].push_back({y, c});
	}

	memset(dist, 0x7F, sizeof(dist));
	dist[1] = 0;

	set<int, cmp> s;
	s.insert(1);

	while (!s.empty()) {
		int curr = *s.begin();
		s.erase(curr);

		for (const auto &[neigh, cost] : G[curr])
			if (dist[curr] + cost < dist[neigh]) {
				dist[neigh] = dist[curr] + cost;
				s.insert(neigh);
			}
	}

	for (int i = 2; i <= n; ++i)
		printf("%d ", dist[i] == INF ? 0 : dist[i]);
	puts("");
}