Cod sursa(job #1916175)

Utilizator andreigasparoviciAndrei Gasparovici andreigasparovici Data 9 martie 2017 08:03:49
Problema Ubuntzei Scor 5
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.89 kb
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>

#define NMAX 2005
#define KMAX 16
#define INF 0x3f3f3f3f
#define pb push_back
#define mkp make_pair

using namespace std;

vector<pair<int,int>> graph[NMAX];
int n, m, k, c[KMAX], d[NMAX], dp[(1<<KMAX)][NMAX], cost[NMAX][NMAX], where[KMAX];

void read()
{
    scanf("%d %d %d ",&n,&m,&k);
    for(int i=0;i<k;i++)
    {
        scanf("%d ",&c[i]);
        where[c[i]]=i;
    }
    c[k]=n;
    where[n]=k++;
    for(int i=1;i<=m;i++)
    {
        int node1, node2, cst;
        scanf("%d %d %d ",&node1,&node2,&cst);
        graph[node1].pb(mkp(node2,cst));
        graph[node2].pb(mkp(node1,cst));
    }
}

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

    priority_queue<int, vector<int> >q;
    q.push(-start_node);

    while(!q.empty())
    {
        int current_node = -q.top();
        q.pop();
        for(auto &it:graph[current_node])
        {
            if(d[it.first] > d[current_node] + it.second)
            {
                d[it.first] = d[current_node] + it.second;
                q.push(-it.first);
            }
        }
    }
}

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

void dynamic()
{
    int q=(1<<k)-1;
    for(int i=0;i<=q;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];

    for(int i=1;i<=q;i++)
        for(int j=0;j<k;j++)
            if(i&(1<<j))
                for(int t=0;t<k;t++)
                    if(i&(1<<t))
                        dp[i][j]=min(dp[i][j],dp[i^(1<<j)][t]+cost[t][c[j]]);

    printf("%d\n",dp[q][where[n]]);
}

int main()
{
    freopen("ubuntzei.in","r",stdin);
    freopen("ubuntzei.out","w",stdout);

    read();
    compute_costs();
    dynamic();

    return 0;
}