Cod sursa(job #892989)

Utilizator ionutmodoModoranu Ionut-Vlad ionutmodo Data 26 februarie 2013 12:32:13
Problema Ubuntzei Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.23 kb
#include <cstdio>
#include <vector>
#include <queue>
#define inf 2000000000
using namespace std;

struct NOD{int x,c;};
vector<NOD> L[2013];
queue<int> Q;
int n, m, k;
int loc[20], d[2012],dist[15][2013],best[15][(1<<15)];

void Read()
{
    int i,x,y;
    NOD aux;
    freopen("ubuntzei.in","r",stdin);
    scanf("%d %d", &n, &m);
    scanf("%d",&k);
    for(i=0; i<k; i++)
        scanf("%d",&loc[i]);
    for(i=1; i<=m; i++)
    {
        scanf("%d %d %d", &x, &y, &aux.c);
        aux.x = y;
        L[x].push_back(aux);
        aux.x = x;
        L[y].push_back(aux);
    }
}
void Initializare(int v[])
{
    for(int i=1; i<=n; i++)
        v[i] = inf;
}
void Bellmanford(int nod, int v[])
{
    Initializare(v);
    v[nod] = 0;
    Q.push(nod);
    while(!Q.empty())
    {
        int k = Q.front();
        Q.pop();
        vector<NOD>::iterator it;
        for(it=L[k].begin(); it!=L[k].end(); it++)
        {
            NOD aux = *it;
            if(v[aux.x] > v[k] + aux.c)
            {
                v[aux.x] = v[k] + aux.c;
                Q.push(aux.x);
            }
        }
    }
}
void Solve()
{
    Bellmanford(1,d);
    if(k==0)
    {
        freopen("ubuntzei.out","w",stdout);
        printf("%d\n", d[n]);
        return;
    }

    int i,j;
    for(i=0; i<k; i++)
        Bellmanford(loc[i],dist[i]);

    int nrmul = (1<<k)-1;
    for(int mul = 1; mul <= nrmul; mul++)
    {
        bool ok = false;
        for(i=0; i<k && !ok; i++)
            if(mul == (1<<i))
            {
                ok = true;
                best[i][mul] = d[loc[i]];
            }

        if(!ok)
        {
            for(i=0; i<k; i++)
            {
                best[i][mul] = inf;
                if((mul & (1<<i)) != 0)
                    for(j=0; j<k; j++)
                        if(i != j && (mul & (1<<j) != 0))
                            best[i][mul] = min(best[i][mul],best[j][mul-(1<<i)]+dist[j][loc[i]]);
            }
        }
    }
    int sol = inf;
    for(i=0; i<k; i++)
        sol = min(sol, best[i][nrmul] + dist[i][n]);
    freopen("ubuntzei.out","w",stdout);
    printf("%d\n", sol);
}
int main()
{
    Read();
    Solve();
    return 0;
}