Cod sursa(job #2947722)

Utilizator andrei_C1Andrei Chertes andrei_C1 Data 26 noiembrie 2022 17:20:51
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 5e4;
const int INF = 2e9;

int N, M;

struct Edge {
	int to, cost;
};

queue<int> q;
bool inQ[NMAX + 1];
vector<Edge> adj[NMAX + 1];
int dist[NMAX + 1];

int main() {
	fin >> N >> M;

	for(int i = 1; i <= M; i++) {
		int A, B, C;
		fin >> A >> B >> C;

		adj[A].push_back(Edge{B, C});
	}

	for(int i = 1; i <= N; i++) {
		dist[i] = INF;
	}
	dist[1] = 0;
	q.push(1);
	inQ[1] = 1;

	while(!q.empty()) {
		int u = q.front();
		q.pop();
		inQ[u] = 0;

		for(const Edge edge: adj[u]) {
			if(dist[edge.to] > dist[u] + edge.cost) {
				dist[edge.to] = dist[u] + edge.cost;

				if(!inQ[u]) {
					q.push(edge.to);
					inQ[edge.to] = 1;
				}
			}
		}
	}

	for(int i = 2; i <= N; i++) {
		if(dist[i] == INF) {
			dist[i] = 0;
		}
		fout << dist[i] << " ";
	}
	return 0;
}