Cod sursa(job #1016082)

Utilizator Cosmin1490Balan Radu Cosmin Cosmin1490 Data 25 octombrie 2013 18:25:03
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iterator>
#include <assert.h>
using namespace std;

const string file = "dijkstra";

const string infile = file + ".in";
const string outfile = file + ".out";

const int INF = 0x3f3f3f3f;


int N, M;
vector<int> dist;
vector<vector<pair<int, int> > > G;


void Dijkstra()
{
	priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > heap;

	dist.resize(N + 1, INF);
	dist[1] = 0;
	heap.push(make_pair(0, 1));
	while(heap.empty() == false)
	{
		pair<int, int> c = heap.top();
		heap.pop();
		int cost = c.first;
		int x = c.second;

		if(dist[x] != cost)
			continue;

		for(vector<pair<int, int> >::iterator itr = G[x].begin();
			itr != G[x].end(); 
			itr++)
		{
			int newDist = dist[x] + itr->second;
			if(dist[itr->first] > newDist)
			{
				dist[itr->first] = newDist;
				heap.push(make_pair(dist[itr->first], itr->first));
			}
		}

	}


}

int main()
{
	fstream fin(infile.c_str(), ios::in);
	fin >> N >> M;
	G.resize(N + 1);
	for(int i = 0; i < M; i++)
	{
		int x, y, c;
		fin >> x >> y >> c;
		G[x].push_back(make_pair(y, c));
	}
	fin.close();

	Dijkstra();
	fstream fout(outfile.c_str(), ios::out);
	for(int i = 2; i <= N; i++)
	{
		fout << (dist[i] == INF ? 0 : dist[i]) << " ";
	}
	fout << "\n";
	fout.close();
}