Cod sursa(job #419458)

Utilizator ooctavTuchila Octavian ooctav Data 17 martie 2010 15:36:06
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <cstdio>
#include <vector>
#include <queue>
#define NMAX 50008
#define INF 1000000001
using namespace std;
int N ,M, NR;
vector< pair<int,int> > v[NMAX];
int viz[NMAX], cost[NMAX];

void citire()
{
	scanf("%d%d",&N,&M);
	int x , y , c;
	for(int i = 1 ; i <= M ; i++)
	{
		scanf("%d %d %d",&x ,&y ,&c);
		v[x].push_back(make_pair(y, c));
	}
}

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

priority_queue<int , vector<int> ,cmp> Q;

void rezolva()
{
	vector<pair<int, int> >::iterator it;
	
	for(int i = 2 ; i <= N ; i++)
		cost[i] = INF;
	
	Q.push(1);
	while(!Q.empty())
	{
		int min = Q.top();
		viz[min] = 0;
		Q.pop();
		for(it = v[min].begin() ; it != v[min].end() ; it++)
			if(cost[it->first] > cost[min] + it->second)
			{
				cost[it->first] = cost[min] + it -> second;
				if(!viz[it->first])
				{
					Q.push(it->first);
					viz[it->first] = NR;
				}
			}
	}
	
}

void scrie()
{
	for(int i = 2 ; i <= N ; i++)
		if(cost[i] == INF)
			printf("0 ");
		else
			printf("%d ",cost[i]);
}

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