Cod sursa(job #1873450)

Utilizator Rocamadour1497Alexandru Martiniuc Rocamadour1497 Data 9 februarie 2017 01:55:39
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <iostream>
#include <cstdio>
#include <fstream>
using namespace std;

const int inf = 1 << 20;
FILE *in = fopen("dijkstra.in", "r"), *out = fopen("dijkstra.out", "w");
int n, m;

int d[1000], q[1000];
struct graph
{
	int cost;
	int nod;
	graph* next;
};
graph* a[1000];
void add(int where, int what, int cost)
{
	graph* q = new graph;
	q->nod = what;
	q->cost = cost;
	q->next = a[where];
	a[where] = q;
}
void read()
{
	fscanf(in, "%d %d", &n, &m);

	int x, y, z;
	for (int i = 1; i <= m; ++i)
	{
		fscanf(in, "%d %d %d", &x, &y, &z);
		add(x, y, z);
	}
}



void dijk()
{
	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;
		graph* 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();
	dijk();
	for (int i = 2; i <= n; ++i)
		fprintf(out, "%d ", d[i] == inf ? 0 : d[i]);
	fprintf(out, "\n");
}