Cod sursa(job #2198736)

Utilizator ioanamoraru14Ioana Moraru ioanamoraru14 Data 25 aprilie 2018 11:21:00
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <iostream>

using namespace std;

const int kNmax = 50005;
const int inf = 10000000;

class Task {
 public:
	void solve() {
		read_input();
		print_output(get_result());
	}

 private:
	int n;
	int m;
	vector<pair<int,int> > adj[kNmax];

	void read_input() {
		ifstream fin("dijkstra.in");
		fin >> n >> m;
		for (int i = 1, x, y, c; i <= m; i++) {
			fin >> x >> y >> c;
			adj[x].push_back(make_pair(y, c));
		}
		fin.close();
	}

	vector<int> get_result() {
		priority_queue<pair<int, int> > q;
		vector<int> d(n + 1, inf);

		d[1] = 0;
		q.push(make_pair(0, 1));

		while (!q.empty()) {
			int u = q.top().second;
			int dist = q.top().first;
			q.pop();

			if (d[u] <  dist) {
				continue;
			}

			for (unsigned int i = 0; i < adj[u].size(); i++) {
				int nod = adj[u][i].first;
				if (d[nod] > d[u] + adj[u][i].second) {
					d[nod] = d[u] + adj[u][i].second;
					q.push(make_pair(d[nod], nod));
				}
			}
		}

		return d;
	}

	void print_output(vector<int> result) {
		ofstream fout("dijkstra.out");
		for (int i = 2; i < int(result.size()); i++) {
			if (result[i] == inf) {
				fout << 0 << ' ';
			}
			else {
				fout << result[i] << ' ';
			}
		}
		fout << '\n';
		fout.close();
	}
};

int main() {
	Task *task = new Task();
	task->solve();
	delete task;
	return 0;
}