Cod sursa(job #640918)

Utilizator mihaibogdan10Mihai Bogdan mihaibogdan10 Data 26 noiembrie 2011 19:07:17
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include<cstdio>
#include<vector>
#include<set>
#define inf 0xfffffff
#define Check() if (++pozitie == 8192){fread (buff, 1, 8192, stdin); pozitie = 0;}
using namespace std;

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

void citeste(int &nr){
	nr = 0;
	while (buff[pozitie] < '0' || buff[pozitie] > '9') Check()
	while (buff[pozitie] >= '0' && buff[pozitie] <= '9'){
		nr = nr * 10 + (buff[pozitie] - '0');
		Check()
	}
}

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

int main(){
	freopen("dijkstra.in", "r", stdin);
	freopen("dijkstra.out", "w", stdout);
	citeste(n); citeste(m);
	int i, x, y, c;
	
	for (i = 0; i < m; i++){
		citeste(x); citeste(y); citeste(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++) printf("%d ", cost[i] != inf ? cost[i] : 0);
	return 0;
}