Cod sursa(job #1226053)

Utilizator vladrochianVlad Rochian vladrochian Data 4 septembrie 2014 14:55:45
Problema Ubuntzei Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.85 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
const int NMAX = 2005, INF = 2069069069;

int N, M, K, hsize, heap[NMAX], pos[NMAX], dist[NMAX], d[NMAX][NMAX], dsmin = INF;
vector<pair<int, int>> G[NMAX];
vector<int> chk;

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

bool cmp(int x, int y) {
	return dist[heap[x]] < dist[heap[y]];
}
void hswap(int x, int y) {
	swap(heap[x], heap[y]);
	swap(pos[heap[x]], pos[heap[y]]);
}
int minson(int x) {
	x <<= 1;
	if (x > hsize)
		return 0;
	if (x < hsize && cmp(x + 1, x))
		++x;
	return x;
}
void upheap(int x) {
	while (x > 1 && cmp(x, x >> 1)) {
		hswap(x, x >> 1);
		x >>= 1;
	}
}
void downheap(int x) {
	int son;
	while ((son = minson(x)) && cmp(son, x)) {
		hswap(x, son);
		x = son;
	}
}

void dijkstra(int src) {
	hsize = N;
	for (int i = 1; i <= N; ++i) {
		heap[i] = pos[i] = i;
		dist[i] = INF;
	}
	dist[src] = 0;
	upheap(src);
	while (hsize > 1) {
		int node = heap[1];
		hswap(1, hsize--);
		downheap(1);
		for (auto it : G[node]) {
			int newdist = dist[node] + it.second;
			if (newdist < dist[it.first]) {
				dist[it.first] = newdist;
				upheap(pos[it.first]);
			}
		}
	}
	for (int node : chk)
		d[src][node] = dist[node];
	d[src][N] = dist[N];
}

int main() {
	fin >> N >> M >> K;
	while (K--) {
		int x;
		fin >> x;
		chk.push_back(x);
	}
	while (M--) {
		int x, y, c;
		fin >> x >> y >> c;
		G[x].push_back(make_pair(y, c));
		G[y].push_back(make_pair(x, c));
	}
	dijkstra(1);
	for (int node : chk)
		dijkstra(node);
	sort(chk.begin(), chk.end());
	do {
		int crt = d[1][chk[0]] + d[chk.back()][N];
		for (size_t i = 1; i < chk.size(); ++i)
			crt += d[chk[i-1]][chk[i]];
		dsmin = min(dsmin, crt);
	} while (next_permutation(chk.begin(), chk.end()));
	fout << dsmin << "\n";
	return 0;
}