Cod sursa(job #877712)

Utilizator tsubyRazvan Idomir tsuby Data 13 februarie 2013 08:09:52
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <cstdio>
#include <vector>
#include <queue>

#define NMAX 50002
#define INFINITY (1 << 30)

using namespace std;

int n, m, d[NMAX];

struct cmp
{
	bool operator() (const int a, const int b)
	{
		return d[a] > d[b];
	}
};

vector < pair <int, int> > G[NMAX];
priority_queue <int, vector<int>, cmp> Q;

void citire()
{
	scanf("%d %d", &n, &m);
	for(int i = 1; i <= n; i++)
	{
		int x, y, cost;
		scanf("%d %d %d", &x, &y, &cost);
		G[x].push_back(make_pair(y,cost));
	}
}

void afisare()
{
	for(int i = 2; i <= n; i++)
		if(d[i] != INFINITY)
			printf("%d ", d[i]);
		else
			printf("0 ");
}

void dijkstra(int v)
{
	for(int i = 1; i <= n; i++)
	{
		d[i] = INFINITY;
		Q.push(i);
	}
	d[v] = 0;
	while(!Q.empty())
	{
		int x = Q.top();
		Q.pop();
		int l = G[x].size();
		for(int i = 0; i < l; i++)
		{
			int y = G[x][i].first;
			int c = G[x][i].second;
			if(d[y] > d[x] + c)
			{
				d[y] = d[x] + c;
				Q.push(y);
			}
		}
	}
}

int main()
{
	freopen("dijkstra.in", "r", stdin);
	freopen("dijkstra.out", "w", stdout);
	citire();
	dijkstra(1);
	afisare();
	return 0;
}