Cod sursa(job #3201223)

Utilizator AndreiMLCChesauan Andrei AndreiMLC Data 7 februarie 2024 10:29:12
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

const int nmax = 50005;
int n, m;
vector<pair<int, int>>G[nmax];
bool viz[nmax];
int dist[nmax];
int inf = INT_MAX;
void read()
{
	f >> n >> m;
	int x, y, c;
	for (int i = 1; i <= m; i++)
	{
		f >> x >> y >> c;
		G[x].push_back({y,c});
	}
}

priority_queue<pair<int, int>>pq;

void dijkstra()
{
	pq.push({0,1});
	while (!pq.empty())
	{
		pair<int, int>varf = pq.top();
		int nod = varf.second;
		pq.pop();

		if (viz[nod])
		{
			continue;
		}

		viz[nod] = 1;

		for (auto it : G[nod])
		{
			if (!viz[it.first] && dist[it.first] > dist[nod] + it.second)
			{
				dist[it.first] = dist[nod] + it.second;
				pq.push({ -dist[it.first], it.first});
			}
		}
	}
}

int main()
{
	read();
	for (int i = 2; i <= n; i++)
	{
		dist[i] = inf;
	}
	dijkstra();
	for (int i = 2; i <= n; i++) {
		if (dist[i] == INT_MAX) {
			g << 0 << " ";
		}
		else {
			g << dist[i] << " ";
		}
	}
}