Cod sursa(job #3323074)

Utilizator TeodoRazvanStancu Teodor-Razvan TeodoRazvan Data 16 noiembrie 2025 21:29:38
Problema Ubuntzei Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.04 kb
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
#include <bits/stdc++.h>

using namespace std;

ifstream fin("ubuntzei.in");
ofstream fout("ubuntzei.out");

const int INF=1e9+2;
vector<int>v;
int cost[2005][2005],n,m,k,dp[(1<<17)+25][25],x,y,c,vs;
vector<vector<pair<int,int>>>a;

struct str{
    int nod,cost;
    bool operator < (const str & aux) const {
        return cost>aux.cost;
    }
};

void dijk(int idx) {
    int stn=v[idx];
    vector<int>d(n+1,INF-1);
    d[stn]=0;
    priority_queue<str>pq;
    pq.push({stn,0});
    while(!pq.empty()) {
        int nod=pq.top().nod,cost=pq.top().cost;
        pq.pop();
        if (cost>d[nod]) continue;
        for (auto f:a[nod]) {
            if (d[f.first]>d[nod]+f.second) {
                d[f.first]=d[nod]+f.second;
                pq.push({f.first,d[f.first]});
            }
        }
    }
    for (int j=0;j<vs;j++) {
        int nod=v[j];
        cost[idx][j]=d[nod];
    }
}

int main() {
    fin>>n>>m>>k;
    v.push_back(1);
    v.push_back(n);
    a.resize(n+1);
    for (int i=0;i<k;i++) {
        fin>>x;
        if (x!=n&&x!=1) v.push_back(x);
    }
    vs=v.size();
    for (int i=0;i<=2001;i++) {
        for (int j=0;j<=2001;j++) {
            cost[i][j]=INF;
        }
    }
    for (int i=1;i<=m;i++) {
        fin>>x>>y>>c;
        a[x].push_back({y,c});
        a[y].push_back({x,c});
    }
    for (int i=0;i<vs;i++) dijk(i);
    for (int i=0;i<(1<<17);i++) {
        for (int j=0;j<vs;j++) {
            dp[i][j]=INF;
        }
    }
    dp[1][0]=0;
    for (int i=0;i<(1<<vs);i++) {
        for (int j=0;j<vs;j++) {
            if (i&(1<<j)) {
                for (int k=0;k<vs;k++) {
                    if ((i&(1<<k))==0) {
                        dp[i|(1<<k)][k]=min(dp[i|(1<<k)][k],dp[i][j]+cost[j][k]);
                    }
                }
            }
        }
    }
    int rez=INF;
    for (int i=0;i<vs;i++) {
        if (dp[(1<<vs)-1][i]!=INF&&cost[i][1]!=INF) {
            rez=min(rez,dp[(1<<vs)-1][i]+cost[i][1]);
        }
    }
    fout<<rez;
    return 0;
}