Cod sursa(job #1243667)

Utilizator silidragosSilion Dragos silidragos Data 16 octombrie 2014 10:25:55
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include<iostream>
#include<fstream>
using namespace std;

const int maxn = 50001;
const int inf = 1 << 30;
ifstream f("djikstra.in", ios::in);
ofstream g("djikstra.out",ios::out);

struct graf{
	int nod, cost;
	graf *next;
};

int n, m;
graf *a[maxn];
int d[maxn], q[maxn];

void add(int x, int y, int z){
	graf *q = new graf;
	q->nod = y;
	q->cost = z;
	q->next = a[x];
	a[x] = q;

}

void read(){
	f >> n >> m;

	int x, y, z;
	for (int i = 1; i <= m; ++i){
		f >> x >> y >> z;
		add(x, y, z);
	}

}

void djikstra(){

	for (int i = 2; i <= n; ++i)
		d[i] = inf;
	
	int min, pmin = 0;
	for (int i = 1; i <= n; ++i){
		min = inf;
		for (int j = 1; j <= n; ++j){
			if (d[j] < min && !q[j])
				min = d[j], pmin = j;
		}

		q[pmin] = 1;
		graf *t = a[pmin];
		while (t){
			if (d[t->nod]>d[pmin] + t->cost)
				d[t->nod] = d[pmin] + t->cost;

			t = t->next;

		}
	}


}

int main(){
	read();
	djikstra();

	for (int i = 2; i <= n; ++i)
		g<<((d[i] == inf)? 0 : d[i])<<" ";
	g << "\n";

	return 0;


}