Cod sursa(job #903226)

Utilizator GheorgheMihaiMihai Gheorghe GheorgheMihai Data 1 martie 2013 19:17:00
Problema Ubuntzei Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.77 kb
#include <stdio.h>
#include <string.h>

#include <queue>
#include <algorithm>
#include <vector>

using namespace std;

int n, m, k;
int c[2005], special[20];
vector <pair <int, int> > v[2005];
int cost[20][20];
int d[131100][18];

void dijkstra (int k)
{
	priority_queue <pair <int, int>, vector <pair <int, int> >, greater <pair <int, int> > > h;
	
	h.push (make_pair (0, special[k]));
	int viz[2005] = {0};
	memset (c, -1, sizeof (c));
	
	int nod, cost;
	
	while (!h.empty())
	{
		nod = h.top().second;
		cost = h.top().first;
		h.pop ();
		viz[nod] = 1;
		if (c[nod] != -1)
			continue;
		c[nod] = cost;
		for (vector <pair <int, int> > :: iterator it = v[nod].begin(); it != v[nod].end(); it ++)
			if (!viz[it -> second])
			{
				h.push (make_pair (it -> first + cost, it -> second));
			}
	}
}

void rez ()
{
	int i, j, lim = (1 << k) - 1, st;
	
	memset (d, 0x3f3f3f3f, sizeof (d));
	d[1][1] = 0;
	
	for (st = 1; st <= lim; st ++)
	{
		for (i = 1; i <= k; i ++)
			if (st & (1 << i - 1))
			{
				for (j = 1; j <= k; j ++)
					if (!(st & (1 << j - 1)))
						d[st | (1 << j - 1)][j] = min (d[st | (1 << j - 1)][j], d[st][i] + cost[i][j]);
			}
	}
	printf ("%d\n", d[lim][k]);
}

int main ()
{
	freopen ("ubuntzei.in", "r", stdin);
	freopen ("ubuntzei.out", "w", stdout);
	
	scanf ("%d %d %d", &n, &m, &k);
	
	int i, j, x, y, z;
	
	special[1] = 1;
	for (i = 2; i <= k+1; i++)
		scanf ("%d", &special[i]);
	k += 2;
	special[k] = n;
	
	for (i = 1; i <= m; i ++)
	{
		scanf ("%d %d %d", &x, &y, &z);
		
		v[x].push_back (make_pair (z, y));
		v[y].push_back (make_pair (z, x));
	}
	
	for (i = 1; i <= k; i ++)
	{
		dijkstra (i);
		for (j = 1; j <= k; j ++)
			cost[i][j] = c[special[j]];
	}
	
	rez ();
	return 0;
}