Cod sursa(job #2644038)

Utilizator sebimihMihalache Sebastian sebimih Data 22 august 2020 22:56:25
Problema Ubuntzei Scor 5
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.02 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <limits.h>
#include <set>

using namespace std;

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

const int N = 2005, inf = INT_MAX;

vector<pair<int, int>> g[N];	
vector<int> OrasCuPrieten;
bool vizitat[N];
int n, m, k, CostTotal = inf, dp[N][N];

void Init()
{
	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			dp[i][j] = inf;
		}
	}
}

void Dijkstra(int start)
{
	set<pair<int, int>> heap;	// cost spre nod
	heap.insert({ 0, start });
	dp[start][start] = 0;

	while (!heap.empty())
	{
		int nod = heap.begin()->second;
		int cost = heap.begin()->first;
		heap.erase(heap.begin());

		for (auto neigh : g[nod])
		{
			int NextNod = neigh.first;
			int NextCost = neigh.second;

			if (cost + NextCost < dp[start][NextNod])
			{
				if (dp[start][NextNod] != inf)
				{
					heap.erase(heap.find({ dp[start][NextNod], NextNod }));
				}

				dp[start][NextNod] = cost + NextCost;
				heap.insert({ dp[start][NextNod], NextNod });
			}
		}
	}
}

void GasesteRuta(int start)
{
	vizitat[start] = true;

	if (start == n)
	{
		return;
	}

	int DrumMin = inf, NextOras = n;
	for (int oras : OrasCuPrieten)
	{
		if (!vizitat[oras])
		{
			if (dp[start][oras] < DrumMin)
			{
				DrumMin = dp[start][oras];
				NextOras = oras;
			}
		}
	}

	if (DrumMin == inf)
	{
		DrumMin = dp[start][NextOras];
	}

	CostTotal += DrumMin;

	GasesteRuta(NextOras);
}

int main()
{
	fin >> n >> m >> k;

	for (int i = 0; i < k; i++)
	{
		int oras;
		fin >> oras;
		OrasCuPrieten.push_back(oras);
	}

	for (int i = 0; i < m; i++)
	{
		int x, y, cost;
		fin >> x >> y >> cost;
		g[x].push_back({ y, cost });
		g[y].push_back({ x, cost });
	}

	Init();

	int StartOras = 1;
	for (int oras : OrasCuPrieten)
	{
		Dijkstra(oras);

		if (dp[oras][1] < CostTotal)
		{
			CostTotal = dp[oras][1];
			StartOras = oras;
		}
	}

	GasesteRuta(StartOras);

	fout << CostTotal;
}