Cod sursa(job #2132363)

Utilizator RG1999one shot RG1999 Data 15 februarie 2018 18:39:45
Problema Ubuntzei Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.76 kb
#include <bits/stdc++.h>

using namespace std;
typedef pair< int ,int > pereche;
int cst[20][2001],i,j,n,m,x,y,nd,k,pt[2001],z,dp[1<<16][20],pw,ans,l;
vector <pereche> v[2001];
priority_queue <pereche, vector<pereche>, greater<pereche> > q;
int ok(int a,int b)
{
    return a&(1<<(b-1));
}
int main()
{
    freopen("ubuntzei.in","r",stdin);
    freopen("ubuntzei.out","w",stdout);
    scanf("%d%d",&n,&m);
    scanf("%d",&k);
    for(i=1;i<=k;i++) scanf("%d",&pt[i]);
    pt[k+1]=1;
    for(i=1;i<=m;i++)
    {
        scanf("%d%d%d",&x,&y,&z);
        v[x].push_back({y,z});
        v[y].push_back({x,z});
    }
    for(i=1;i<=k+1;i++)
    {
        q.push({0,pt[i]});
        while(!q.empty())
        {
            nd=q.top().second;
            q.pop();
            for(j=0;j<v[nd].size();j++)
                if(cst[i][v[nd][j].first]>cst[i][nd]+v[nd][j].second||!cst[i][v[nd][j].first])
            {
                cst[i][v[nd][j].first]=cst[i][nd]+v[nd][j].second;
                q.push({cst[i][v[nd][j].first],v[nd][j].first});

            }
        }

    }
    if(k==0)
    {
        printf("%d\n",cst[k+1][n]);
        return 0;
    }
    pw=1<<k;
    for(j=1;j<pw;j++)
    {
        for(i=1;i<=k;i++)
        if(j==1<<(i-1))
        break;
        if(i<=k)
        {
            dp[j][i]=cst[k+1][pt[i]];
            continue;
        }
        for(i=1;i<=k;i++)
        {
            dp[j][i]=999999999;
            if(ok(j,i))
            for(l=1;l<=k;l++)
                if(i!=l&&ok(j,l))
                dp[j][i]=min(dp[j][i],dp[j-(1<<(i-1))][l]+cst[l][pt[i]]);
        }

    }
    ans=999999999;
    for(i=1;i<=k;i++)
        ans=min(ans,dp[(1<<k)-1][i]+cst[i][n]);
    printf("%d\n",ans);
        return 0;
}