Cod sursa(job #2516245)

Utilizator PaulTPaul Tirlisan PaulT Data 30 decembrie 2019 19:50:37
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

struct Node {
	int x, d;
	
	friend bool operator < (const Node& a, const Node& b)
	{
		return a.d > b.d;
	}
};

using VI = vector<int>;
using VN = vector<Node>;
using VVN = vector<VN>;

const int Inf = 0x3f3f3f3f;
VVN G;
VI d;
int n, m;

void Read();
void Dijkstra(int root, VI& d);
void Write();

int main()
{
	Read();
	Dijkstra(1, d);
	Write();
}

void Dijkstra(int x, VI& d)
{
	priority_queue<Node> Q;
	d = VI(n + 1, Inf);
	d[x] = 0;
	Q.push({x, 0});
	
	int y, w;
	while (!Q.empty())
	{
		x = Q.top().x;
		w = Q.top().d;
		Q.pop();
		if (w > d[x])
			continue;
		for (const Node& node : G[x])
		{
			y = node.x;
			w = node.d;
			if (d[y] > d[x] + w)
			{
				d[y] = d[x] + w;
				Q.push({y, w});
			}
		}
	}
}

void Write()
{
	ofstream fout("dijkstra.out");
	for (int i = 2; i <= n; i++)
		if (d[i] == Inf)
			fout << "0 ";
		else
			fout << d[i] << ' ';
}

void Read()
{
	ifstream fin("dijkstra.in");
	fin >> n >> m;
	G = VVN(n + 1);
	
	int x, y, w;
	while (m--)
	{
		fin >> x >> y >> w;
		G[x].push_back({y, w});
	}
}