Cod sursa(job #701243)

Utilizator psycho21rAbabab psycho21r Data 1 martie 2012 14:42:13
Problema Ubuntzei Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.29 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define INF 999999999

using namespace std;
int N, M, K;
typedef pair<int,int> edge;
vector< vector<edge> > graph(50001);
int map[1<<15][15], path[15][10005];
void dijkstra(int source, int *dis)
{
    int v;
    for (int i = 1; i <= N; ++i)
		dis[i] = INF;
    dis[source] = 0;
    priority_queue <edge, vector<edge>, greater<edge> > S;
    for (int i = 1; i <= N; ++i)
        S.push(make_pair(dis[i], i));
    for(int i = 1; i < N; ++i)
    {
        pair <int, int> top = S.top();
        S.pop();
        int node = top.second;
        if(dis[node] < top.first)
            continue;
        for(int j = 0; j < graph[node].size(); ++j)
        {
            if(dis[v = graph[node][j].first] > dis[node] + graph[node][j].second)
            {
                dis[v] = dis[node] + graph[node][j].second;
                S.push(make_pair(dis[v], v));
            }
        }
    }
}

int main()
{
    vector <int> custom_path;
    ifstream in("ubuntzei.in");
    in >> N >> M >> K;
    for(int a, i = 0; i < K; ++i)
    {
        in >> a;
        custom_path.push_back(a);
    }
    for (int a, b, c; M; --M)
    {
        in >> a >> b >> c;
        graph[a].push_back(make_pair(b,c));
        graph[b].push_back(make_pair(a,c));
    }
    in.close();
    int dis[10005];
    dijkstra(1, dis);
    ofstream out("ubuntzei.out");
    if(K == 0)
    {
        out << dis[N];
        return 0;
    }
    for (int i = 0; i < K; ++i)
		dijkstra(custom_path[i], path[i]);
    for(int i = 1; i < (1<<K); ++i)
    {
        int j;
        for(j = 0; j < K; ++j)
            if (i == (1<<j))
				break;
        if (j < K && i == (1<<j))
        {
            map[i][j] = dis[custom_path[j]];
            continue;
        }
        for(j = 0; j < K; ++j)
        {
            map[i][j] = INF;
            if(i & (1<<j))
                for(int k = 0; k < K; ++k)
                    if(k != j && (i & (1<<j)))
                        map[i][j] = min(map[i][j], map[i-(1<<j)][k] + path[k][custom_path[j]]);
        }
    }
    int smallest = INF;
	for (int i = 0; i < K; ++i)
		smallest = min(smallest, map[(1<<K)-1][i] + path[i][N]);
    out << smallest;
    out.close();
    return 0;
}