Cod sursa(job #3200590)

Utilizator eugenioMarinescu Eugenio eugenio Data 5 februarie 2024 10:36:55
Problema Ubuntzei Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.05 kb
#include <bits/stdc++.h>
#define nmax 3005
#define kmax 16
#define inf 2*1e9
using namespace std;

vector<vector<pair<int,int>>> g(nmax);
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;
int n, m, k, x, y, c;
int ub[kmax], cost[kmax+1][nmax], dp[(1<<kmax)+1][kmax+1];

void bfs(int s)
{
    for(int i=1; i<=n; i++)
        cost[s][i]=inf;
    cost[s][s]=0;
    pq.push({0,s});
    while(!pq.empty())
    {
        int nod=pq.top().second;
        pq.pop();
        for(auto x : g[nod])
        {
            int nnod=x.first;
            int ccost=x.second;
            if(cost[s][nnod]>cost[s][nod]+ccost)
            {
                cost[s][nnod]=cost[s][nod]+ccost;
                pq.push({cost[s][nnod],nnod});
            }
        }
    }
}

int main()
{
    ifstream cin("ubuntzei.in");
    ofstream cout("ubuntzei.out");
    cin>>n>>m>>k;
    for(int i=1; i<=k; i++)
        cin>>ub[i];

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

    ub[k+1]=1;
    ub[k+2]=n;

    for(int i=1; i<=k+2; i++)
        bfs(ub[i]);

    if(k==0)
    {
        cout<<cost[1][n];
        exit(0);
    }

    for(int i=1; i<=k; i++)
        for(int mask=1; mask<=((1<<k)-1); mask++)
            dp[mask][i]=inf;

    for(int i=1; i<=k; i++)
        dp[(1<<(i-1))][i]=cost[1][ub[i]];


    for(int mask=1; mask<=((1<<k)-1); mask++)
    {
        if(__builtin_popcount(mask)<2)
            continue;
        for(int j=0; j<k; j++)
        {
            if(mask&(1<<j))
            {
                for(int p=0; p<k; p++)
                {
                    if(mask&(1<<p) && p!=j)
                    {
                        dp[mask][j+1]=min(dp[mask][j+1], dp[mask-(1<<j)][p+1]+cost[ub[p+1]][ub[j+1]]);
                    }
                }
            }
        }
    }

    long long sol=inf;
    for(int i=1; i<=k; i++)
        sol=min(sol,1ll*dp[(1<<k)-1][i] + 1ll*cost[ub[i]][n]);
    cout<<sol;
}