Cod sursa(job #2127027)

Utilizator Tyler_BMNIon Robert Gabriel Tyler_BMN Data 10 februarie 2018 11:32:34
Problema Ubuntzei Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.62 kb
#include <fstream>
#include <vector>
#include <queue>

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

const int MAXN = 2005;
const int INF = 0x3f3f3f3f;
const int MAXK = 16;

int n, m, k;
int c[MAXN], cost[MAXN][MAXN], d[MAXN], dp[1 << MAXK][MAXK];

struct arc {
	int dest;
	int cost;
};
vector<arc> g[MAXN];

void read() {
	fin >> n >> m >> k;

	for (int i = 0; i < k; i++)
		fin >> c[i];

	c[k++] = n;

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

void bellman(int x) {
	fill(d + 1, d + n + 1, INF);
	d[x] = 0;

	queue<int> Q;
	Q.push(x);

	while (!Q.empty()) {
		x = Q.front();
		Q.pop();
		for (auto& y : g[x]) {
			if (d[y.dest] > d[x] + y.cost) {
				d[y.dest] = d[x] + y.cost;
				Q.push(y.dest);
			}
		}
	}
}

void costs() {
	for (int i = 0; i < k; i++) {
		bellman(c[i]);
		for (int j = 0; j <= n; j++)
			cost[i][j] = d[j];
	}
}

void init() {
	for (int i = 0; i < (1 << k); i++)
		for (int j = 0; j < k; j++)
			dp[i][j] = INF;

	for (int i = 0; i < k; i++)
		dp[1 << i][i] = cost[i][1];
}

void hamilton(int drum) {
	for (int nod = 0; nod < k; nod++) {
		if (drum & (1 << nod)) {
			for (int vecin = 0; vecin < k; vecin++) {
				if (drum & (1 << vecin)) {
					dp[drum][nod] = min(dp[drum][nod], dp[drum ^ (1 << nod)][vecin] + cost[vecin][c[nod]]);
				}
			}
		}
	}
}

int main() {

	read();
	costs();
	init();

	for (int drum = 1; drum < (1 << k); drum++)
		hamilton(drum);

	fout << dp[(1 << k) - 1][k - 1];

	return 0;
}