Cod sursa(job #997734)

Utilizator Cosmin1490Balan Radu Cosmin Cosmin1490 Data 14 septembrie 2013 19:56:06
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>
using namespace std;

const string file = "dijkstra";

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

const int INF = 0x3f3f3f3f;
vector<vector<pair<int, int> > > G;
int N, M;
vector<int> dist;


void Dijkstra()
{
	priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > heap;
	heap.push(make_pair(0, 1));
	dist[1] = 0;
	while(heap.empty() == false)
	{
		pair<int, int> p = heap.top();
		heap.pop();
		int cost = p.first;
		int x = p.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(newDist, itr->first));
			}
		}


	}



}

int main()
{
	fstream fin(infile.c_str(), ios::in);
	fin >> N >> M;
	G.resize(N + 1);
	dist.resize(N + 1, INF);
	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++)
	{
		if(dist[i] == INF)
		{
			fout << 0 << " ";
		}
		else 
		{
			fout << dist[i] << " " ;
		}
	}
	fout << "\n";
	fout.close();
}