Cod sursa(job #898746)

Utilizator cremarencodianaCremarenco Diana cremarencodiana Data 28 februarie 2013 11:32:25
Problema Ubuntzei Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.13 kb
#include <cstdio>
# include <queue>
# include <vector>
# include <algorithm>
#define MAXINT 0x7FFFFFFF
using namespace std;

vector < pair <int, int> > v[2013];
queue <int> q;
int dist[16][2013],best[16][(1<<15)],d[2013],loc[2013],i,j,k,sol,n,m,x,y,c,nrmul,mul;

void bellmanford(int nod, int l[])
{
    //q.empty();
    int i;
    for (i=1; i<=n; i++)
         l[i]=MAXINT;
    q.push(nod);
    l[nod]=0;
    while (!q.empty())
    {
        int cur=q.front();
        q.pop();
        vector < pair <int, int > > :: iterator it;
        for (it=v[cur].begin(); it!=v[cur].end(); ++it)
        {
            int vecin=(*it).second;
            int cost=(*it).first;
            if (l[vecin]>l[cur]+cost)
            {
                l[vecin]=l[cur]+cost;
                q.push(vecin);
            }
        }
    }
}



int main()
{
    freopen("ubuntzei.in","r",stdin);
    freopen("ubuntzei.out","w",stdout);
    scanf("%d %d\n",&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\n",&x,&y,&c);
        v[x].push_back(make_pair(c,y));
        v[y].push_back(make_pair(c,x));
    }

    bellmanford(1,d);

    if (k==0)
    {
        printf("%d\n",d[n]);
        return 0;
    }
    for (i=0; i<k; i++)
         bellmanford(loc[i],dist[i]);

    nrmul=(1<<k)-1;
    for (mul=1; mul<=nrmul; ++mul)
    {
        bool ok=false;
        for (i=0; i<k && ok==false; ++i)
            if (mul ==( 1<<i))
            {
                ok=true;
                best[i][mul]=d[loc[i]];
            }
        if (ok==false)
        {
            for (i=0; i<k; i++)
            {
                best[i][mul]=MAXINT;
                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]]);
            }
        }
    }

    sol=MAXINT;
    for (i=0; i<k;i++)
        sol=min(sol,best[i][nrmul]+dist[i][n]);
    printf("%d\n",sol);
    return 0;
}