Cod sursa(job #1373399)

Utilizator abel1090Abel Putovits abel1090 Data 4 martie 2015 18:25:28
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
///DIJKSTRA
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <limits>

using namespace std;

typedef pair<int, int> Edge; ///to, cost	

const int INF = numeric_limits<int>::max();

class Comp {public: bool operator () (Edge& a, Edge& b) {return a.second > b.second;}};

void dijkstra(vector<vector<Edge> >& adjList, vector<int>& answ) {
	priority_queue<Edge, vector<Edge>, Comp> pq;

	answ.assign(adjList.size(), INF);
	answ[0] = 0;

	pq.push(Edge(0, answ[0]));

	int cr, crCost;
	vector<Edge>::iterator i;
	while(!pq.empty()) {
		cr = pq.top().first;
		crCost = pq.top().second;
		pq.pop();

		if(crCost != answ[cr]) continue;

		for(i=adjList[cr].begin(); i!=adjList[cr].end(); ++i) 
			if(crCost + i->second < answ[i->first]) {
				answ[i->first] = crCost + i->second;
				pq.push(Edge(i->first, answ[i->first]));
			}
	}
}

int main() {
	ifstream inStr("dijkstra.in");
	ofstream outStr("dijkstra.out");

	int N, M;
	inStr >> N >> M;

	vector<vector<Edge> > adjList(N);
	
	int fr, to, cst;
	for(int i=0; i<M; ++i) {
		inStr >> fr >> to >> cst;
		adjList[--fr].push_back(Edge(--to, cst));
	}

	vector<int> answ;
	dijkstra(adjList, answ);

	for(int i=1; i<answ.size(); ++i)
		if(answ[i] != INF)
			outStr << answ[i] << ' ';
		else 
			outStr << -1 << ' ';

	outStr << '\n';
	
	return 0;
}