Cod sursa(job #2717877)

Utilizator ardutgamerAndrei Bancila ardutgamer Data 8 martie 2021 09:39:34
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

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

const int NMAX = 50005;
const int INF = 2e9;

struct edge {
	int y, cost;
	bool operator<(const edge& other) const {
		return cost > other.cost;
	}
};

priority_queue<edge>pq;
vector<edge>G[NMAX];

int distMin[NMAX];
bool viz[NMAX];

int m, n;

void dijkstra()
{
	for (int i = 1; i <= n; i++)
		distMin[i] = INF;
	distMin[1] = 0;
	
	viz[1] = true;
	pq.push(edge({ 1,0 }));

	while (!pq.empty())
	{
		edge u = pq.top();
		pq.pop();

		for (edge v : G[u.y])
		{
 			if (!viz[v.y])
			{
				viz[v.y] = true;
				distMin[v.y] = distMin[u.y] + v.cost;
				pq.push(v);
			}
		}
	}
}

int main()
{
	ios_base::sync_with_stdio(false);
	fin.tie(0); fout.tie(0);
	fin >> n >> m;
	while (m--)
	{
		int a, b, c;
		fin >> a >> b >> c;
		G[a].push_back(edge({ b,c }));
		G[b].push_back(edge({ a,c }));
	}
	dijkstra();
	for (int i = 2; i <= n; i++)
		fout << distMin[i] << ' ';
	fout << '\n';
	return 0;
}