Cod sursa(job #640892)

Utilizator mihaibogdan10Mihai Bogdan mihaibogdan10 Data 26 noiembrie 2011 18:31:56
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include<cstdio>
#include<vector>
#include<set>
#define inf 0xfffffff
using namespace std;
FILE *in = fopen("dijkstra.in", "r"), *out = fopen("dijkstra.out", "w");

struct muchie	{int y, c;};
struct nod {int n, c;};
vector <muchie> muchii[50001];
vector <int> cost;
int n, m;

struct compara{
	bool operator()(nod n1, nod n2)	const
		{return n1.c < n2.c;}
};
multiset <nod, compara> heap;

int main(){
	fscanf (in, "%d %d", &n, &m);
	int i, x, y, c;
	
	for (i = 0; i < m; i++){
		fscanf (in, "%d %d %d", &x, &y, &c);
		muchii[x].push_back( (muchie){y, c} );
	}
	cost.assign(n+1, inf);
	cost[1] = 0;
	heap.insert( (nod){1, 0} );
	
	while (!heap.empty()){
		multiset<nod, compara>::iterator it = heap.begin();
		int x = (*it).n;
		
		for (i = 0 ;i < (int)muchii[x].size(); i++){
			y = muchii[x][i].y;
			c = muchii[x][i].c;
			if (cost[y] > cost[x] + c){
				cost[y] = cost[x] + c;
				heap.insert( (nod){y, cost[y]} );
			}
		}
		heap.erase(it);
	}
	
	for (i = 2; i<=n; i++) fprintf(out, "%d ", cost[i]);
	return 0;
}