Cod sursa(job #2454274)

Utilizator ziendeDanut Avadanei ziende Data 7 septembrie 2019 20:32:16
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <vector>
#include <queue>

#define NMax 50004
#define oo 2000000000

using namespace std;
 
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
 
int N, M, a, b, c, dist[NMax];
bool visited[NMax];

vector <pair <int, int>> G[NMax];

queue <int> q;
 
int main() {
 
	int i, currentNode;

    fin >> N >> M;

	for (i = 1; i <= M; i++) {
		fin >> a >> b >> c;
		G[a].push_back({ b, c });
	}
	
	for (i = 2; i <= N; i++) {
		dist[i] = oo;
	}
	
	q.push(1);
	
	while (!q.empty()) {
		currentNode = q.front();
		q.pop();

		if (!visited[currentNode]) {
			visited[currentNode] = true;

			for (auto node : G[currentNode]) {
				if (dist[currentNode] + node.second < dist[node.first]) {
					dist[node.first] = dist[currentNode] + node.second;
					q.push(node.first);
				}
			}
		}
	}

	for (i = 2; i <= N; i++) {
		if (dist[i] == oo) {
			fout << "0 ";
		}
		else {
			fout << dist[i] << " ";
		}
	}
 
    fin.close();
    fout.close();

    return 0;
}