Cod sursa(job #2846703)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 9 februarie 2022 15:57:52
Problema Ubuntzei Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.18 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("ubuntzei.in");
ofstream g("ubuntzei.out");

vector < pair < int , int > > v[2005];
int n,m,k,x,y,c;
long long dp[20][65540];
int cost[25][25];
int dist[2005];
int loc[25];
bool inqueue[2005];

struct compare{
    bool operator()(int a, int b) {
        return dist[a]>dist[b];
    }
};

priority_queue < int , vector < int > , compare > pq;

void read() {
    f >> n >> m >> k;
    loc[1]=1; loc[k+2]=n;
    for (int i=2;i<=k+1;i++) {
        f >> loc[i];
    }
    for (int i=1;i<=m;i++) {
        f >> x >> y >> c;
        v[x].push_back({y,c});
        v[y].push_back({x,c});
    }
}

void init(int p) {
    fill(dist+1,dist+n+1,INT_MAX);
    dist[p]=0;
    inqueue[p]=1;
}


void dijkstra() {
    while (pq.empty()==0) {
        int node = pq.top();
        pq.pop();
        inqueue[node]=0;
        for (auto k:v[node]) {
            if (dist[k.first]>dist[node]+k.second) {
                dist[k.first]=dist[node]+k.second;
                if (inqueue[k.first]==0) {
                    pq.push(k.first);
                    inqueue[k.first]=1;
                }
            }
        }
    }
}

void create_dist(int p) {
    for (int i=1;i<=k+2;i++) {
        cost[p][i]=dist[loc[i]];
        cost[i][p]=dist[loc[i]];
    }
}

void dynamics() {
    for (int i=1;i<=k+2;i++) {
        for (int j=1;j<(1<<(k+2));j++) {
            dp[i][j]=INT_MAX;
        }
    }
    for (int i=1;i<=k+2;i++) {
        dp[i][(1<<(i-1))]=0;
    }
    for (int p=1;p<(1<<(k+2));p++) {
        for (int a=1;a<=k+2;a++) {
            if (((p&(1<<(a-1)))==(1<<(a-1)))) {
                for (int b=1;b<=k+2;b++) {
                    if (a!=b && ((p&(1<<(b-1)))==(1<<(b-1)))) {
                        dp[a][p] = min(dp[a][p],dp[b][p-(1<<(a-1))]+cost[a][b]);
                    }
                }
            }
        }
    }
    g << dp[k+2][(1<<k+2)-1];
}

void solve() {
    for (int i=1;i<=k+1;i++) {
        init(loc[i]);
        pq.push(loc[i]);
        dijkstra();
        create_dist(i);
    }
    dynamics();
}


int main()
{
    read();
    solve();
    return 0;
}