Cod sursa(job #1502452)

Utilizator cristian.caldareaCaldarea Cristian Daniel cristian.caldarea Data 14 octombrie 2015 17:42:38
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
// OK infoarena
#include <fstream>
#include <bitset>
#include <queue>
#include <vector>
using namespace std;
 
using VI = vector<int>;
using PII = pair<int, int>;
using VPII = vector<PII>;
const int Inf = 0x3f3f3f3f;

vector<int> d;

struct Pair {
	int y;
	bool operator < (const Pair& p) const
	{
		return d[y] > d[p.y];
	}
};

priority_queue<Pair> Q;
vector<VPII> G; 
int n, m;
vector<bool> inQ;
void ReadGraph();
void Dijkstra(int k, VI& d);
void Write();

int main()
{
	ReadGraph();
	
	Dijkstra(1, d);
	Write();
}

void Dijkstra(int k, vector<int>& d)
{
	int y, w, dist;      // costul muchiei
	d = vector<int>(n + 1, Inf);
	
	d[k] = 0;
	Q.push({k});
	inQ[k] = true;
	while ( !Q.empty() )
	{
		k = Q.top().y; dist = d[Q.top().y];
		Q.pop();
		inQ[k] = false;
		for (const auto& e : G[k])
		{
			y = e.first; w = e.second; 
			if ( d[y] > d[k] + w )
			{
				d[y] = d[k] + w;
				if ( !inQ[y] )
				{
					Q.push({y});
					inQ[y] = true;
				}
			}
		}
	}
}

void ReadGraph()
{
	ifstream fin("dijkstra.in");
	fin >> n >> m;
	G.resize(n + 1);
	inQ = vector<bool>(n + 1);
	int x, y, w; 
	for (int e = 0; e < m; ++e)
	{
		fin >> x >> y >> w;
		G[x].push_back({y, w}); 
	}
	fin.close();
}

void Write()
{
	ofstream fout("dijkstra.out"); 
	for (int i = 2; i <= n; ++i)
		if ( d[i] != Inf )
			fout << d[i] << ' ';
		else
			fout << 0 << ' ';
	fout.close();
}