Cod sursa(job #2722834)

Utilizator hurjui12AlexandruHurjui Alexandru-Mihai hurjui12Alexandru Data 13 martie 2021 12:29:39
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

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

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

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

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

int main()
{
	int n, m, i, j, x, y, z;
	ei 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({0, 1});
	
	for (i = 1; i < n; i++)
	{
		while (p.empty() == 0 && d[p.top().x] <= p.top().c)
			p.pop();
		if (p.empty() == 1)
			break;
		
		na = p.top();
		p.pop();
		b[na.x] = 1;
		
		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({d[v[na.x][j].first], v[na.x][j].first});
			}
	}
	
	for (i = 2; i<=n; i++)
	{
		if (d[i] < (1<<30))
			fout << d[i] << ' ';
		else
			fout << 0 << ' ';
	}
	return 0;
}