Cod sursa(job #2738921)

Utilizator hurjui12AlexandruHurjui Alexandru-Mihai hurjui12Alexandru Data 6 aprilie 2021 15:46:17
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

ifstream fin ("dijkstra.in");
ofstream fout ("dijkstra.out");

vector <pair <int, int>> v[50001];

struct el
{
	int x, c;
	bool operator < (const el &alt) const
	{
		return c > alt.c;
	}
};

priority_queue <el> p;
int d[50001];
bool b[50001];

int main()
{
	int n, m, i, j, x, y, z;
	el na;
	fin >> n >> m;
	for (i = 1; i<=m; i++)
	{
		fin >> x >> y >> z;
		v[x].push_back({y, z});
	}
	for (i = 1; i<=n; i++)
		d[i] = 1<<30;
	d[1] = 0;
	p.push({1, 0});
	for (i = 1; i<n; i++)
	{
		while (p.empty() == 0 && b[p.top().x] == 1)
			p.pop();
		if (p.empty() == 1)
			break;
		
		na = p.top();
		b[na.x] = 1;
		p.pop();
		
		for (j = 0; j<v[na.x].size(); j++)
			if (d[v[na.x][j].first] > na.c + v[na.x][j].second)
			{
				d[v[na.x][j].first] = na.c + v[na.x][j].second;
				p.push({v[na.x][j].first, d[v[na.x][j].first]});
			}
	}
	for (i = 2; i<=n; i++)
	{
		if (d[i] < (1<<30))
			fout << d[i] << ' ';
		else
			fout << 0 << ' ';
	}
	return 0;
}