Cod sursa(job #877170)

Utilizator alex_mircescuAlex Mircescu alex_mircescu Data 12 februarie 2013 17:21:48
Problema Ubuntzei Scor 95
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.78 kb
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>

#define XX 1000000
#define S second
#define F first

using namespace std;

vector < pair <long, long> > v[2010];

priority_queue< pair<long, long>, vector< pair<long, long> >, greater < pair<long, long> > > q;
long i, n, k, m, K[20], j, x, y, c;
long T[265000][20], V[20][20], cost[2010];

long solve(long a, long b) {
	if (!T[a][b]) {
		T[a][b] = XX;
		for (long i = 0; i < k; ++i) {
			long U = V[i][b];
			long H = 1 << b;
			if (U && a & (1 << i) && i || a == H + 1) {
				T[a][b] = min(T[a][b], solve(a ^ H, i) + U);            
			}
		}
	}
	long u = T[a][b];
	
	if (u == -1) return 0;
    return u;
}

int main () {
	freopen("ubuntzei.in", "r", stdin);
	freopen("ubuntzei.out", "w", stdout);
	
	scanf("%ld %ld\n%ld", &n, &m, &k);
	
	memset(V, 1, sizeof(V));
	
	for (i = 1; i <= k; ++i) scanf("%ld", &K[i]);
	
	while (m--) {
		scanf("%ld %ld %ld", &x, &y, &c);
		v[x].push_back(make_pair(c, y));
		v[y].push_back(make_pair(c, x));
	}
	
	K[0] = 1;
	K[k + 1] = n;
	for (i = 0; i <= k; ++i) {
		cost[K[i]] = -1;
		
		long aux = v[K[i]].size();
		for (j = 0; j < aux; ++j)
			q.push(v[K[i]][j]);
		
		while (!q.empty()) {
			if (!cost[q.top().S]) {
				
				x = q.top().S;
				cost[x] = q.top().F;
				q.pop();
				
				long aux = (long)(v[x].size());
				for (j = 0; j < aux; ++j) {
					if (!cost[v[x][j].S]) {
						v[x][j].F += cost[x];
						q.push(v[x][j]);
						v[x][j].F -= cost[x];
					}
				}
				
				continue;
			}
			q.pop();              
		}
		
		cost[K[i]] = 0;
		
		for (j = 0; j < k + 2; ++j) V[i][j] = cost[K[j]];
		memset(cost, 0, sizeof(cost));
	}
	
	k += 2;
	T[1][0] = -1;
	printf("%ld\n", solve((1 << k) - 1, k - 1));
	return 0;
}