Cod sursa(job #2682760)

Utilizator Andrei21AAnea Andrei Andrei21A Data 9 decembrie 2020 16:14:55
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int nMax = 50001;
const int inf = (1 << 30);
int n, m;
vector <pair<int, int>> l[nMax];
priority_queue <pair <int, int>> q;

bool viz[nMax];
int dist[nMax];

void Citire()
{
	fin >> n >> m;
	int x, y, d;
	for (int i = 0; i <= m; i++)
	{
		fin >> x >> y >> d;
	l[x].push_back({ y, d });
	}
	fin.close();
}

void Dijkstra(int nod)
{
	for (int i = 1; i <= n; i++)
		dist[i] = inf;
	dist[nod] = 0;
	q.push({ 0, nod });
	while (!q.empty())
	{
		int nod = q.top().second;
		int cost = -q.top().first;
		q.pop();
		if (!viz[nod])
		{
			viz[nod] = 1;
			for (auto it : l[nod])
			{
				int newNod = it.first;
				int newCost = it.second;
				if (dist[newNod] > dist[nod] + newCost)
				{
					dist[newNod] =dist[nod] + newCost;
					q.push({ -dist[newNod],newNod });
				}
			}
		}
		


	}
}

int main()
{
	Citire();
	Dijkstra(1);
	for (int i = 2; i <= n; i++)
	{
		if (dist[i] == inf)fout << "0 ";
		else fout << dist[i] << " ";
	}
	fout << "\n";
	return 0;
}