Cod sursa(job #1570437)

Utilizator tudormaximTudor Maxim tudormaxim Data 16 ianuarie 2016 15:39:36
Problema Ubuntzei Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.92 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int nmax = 2005;
const int oo = (1<<29);
vector <pair<int,int> > g[nmax];
int n, m, k, a[20], dist[nmax], d[20][nmax], sol[1<<16][20];

class cmp{
public:
    inline bool operator () (const int &x, const int &y)
    {
        return dist[x] > dist[y];
    }
};

void dijkstra(int start, int lev)
{
    priority_queue <int, vector<int>, cmp> heap;
    int i, dad, son, cost;
    for(i=1; i<=n; i++)
        dist[i]=oo;
    dist[start]=0;
    heap.push(start);
    while(!heap.empty())
    {
        dad=heap.top();
        heap.pop();
        for(i=0; i<g[dad].size(); i++)
        {
            son=g[dad][i].first;
            cost=g[dad][i].second;
            if(dist[dad]+cost < dist[son])
            {
                dist[son]=dist[dad]+cost;
                heap.push(son);
            }
        }
    }
    for(i=1; i<=n; i++)
        d[lev][i]=dist[i];
}

int get_min(int x, int next)
{
    int i;
    if(x==0) return d[0][next];
    int minx = oo;
    for(i=0; i<k; i++)
        if((x &(1<<i))==(1<<i))
            if(minx > sol[x][i]+d[i+1][next])
                minx=sol[x][i]+d[i+1][next];
    return minx;
}

int main()
{
    ifstream fin ("ubuntzei.in");
    ofstream fout ("ubuntzei.out");
    ios_base::sync_with_stdio(false);
    int i, j, x, y, c;
    fin >> n >> m >> k;
    for(i=1; i<=k; i++)
        fin >> a[i];

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

    a[0]=1;
    for(i=0; i<=k; i++)
        dijkstra(a[i], i);

    for(i=1; i<(1<<k); i++)
        for(j=0; j<k; j++)
            if((i&(1<<j))==(1<<j))
                sol[i][j]=get_min(i-(1<<j), a[j+1]);

    fout <<get_min((1<<k)-1, n);
    fin.close();
    fout.close();
    return 0;
}