Cod sursa(job #2956332)

Utilizator Theodor17Pirnog Theodor Ioan Theodor17 Data 19 decembrie 2022 10:05:58
Problema Ubuntzei Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.37 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>

using namespace std;

ifstream cin("ubuntzei.in");
ofstream cout("ubuntzei.out");

const int NMAX = 2e3;
const int inf = 1e9;

int lmin[NMAX + 1][NMAX + 1], dp[NMAX + 1][21], masca;
priority_queue <pair <int, int>, vector <pair <int, int>>, greater <pair <int, int>>> q;
vector <pair <int, int>> g[NMAX + 1];
bitset <NMAX + 1> ad[NMAX + 1];
vector <int> orase;

void dijkstra(int nod){

    /*

        lmin[i][j] = costul minim cu care ajung in orasul j, pornind din orasul i

    */

    q.push({0, nod});
    lmin[nod][nod] = 0;

    while(!q.empty()){

        pair <int, int> x = q.top();
        q.pop();

        for(auto y : g[x.second]){
            if(lmin[nod][y.first] > lmin[nod][x.second] + y.second){

                lmin[nod][y.first] = lmin[nod][x.second] + y.second;
                q.push({lmin[nod][y.first], y.first});

            }
        }

    }

}

int main(){

    ios :: sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int n = 0, m = 0;
    cin >> n >> m;

    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= n; j++){

            lmin[i][j] = inf;

        }
    }


    int k = 0;
    cin >> k;

    orase.push_back(1);
    for(int i = 0; i < k; i++){

        int x = 0;
        cin >> x;

        orase.push_back(x);

    }

    orase.push_back(n);


    for(int i = 0; i < m; i++){

        int x = 0, y = 0, cost = 0;
        cin >> x >> y >> cost;

        g[x].push_back({y, cost});
        g[y].push_back({x, cost});

        ad[x][y] = 1;
        ad[y][x] = 1;

    }


    for(auto e : orase){

        dijkstra(e);

    }

    masca = (1 << (k + 2)) - 1;

    for(int i = 0; i <= masca; i++)
        for(int j = 0; j <= orase.size(); j++)
            dp[i][j] = inf;

    dp[1][0] = 0;

    for(int i = 3; i <= masca; i++){

        for(int j = 1; j < orase.size(); j++){

            if((i & (1 << j)) == 0)
                continue;

            int new_mask = (i ^ (1 << j));

            for(int p = 0; p < orase.size(); p++){

                if((new_mask & (1 << p)))
                    dp[i][j] = min(dp[i][j], dp[new_mask][p] + lmin[orase[p]][orase[j]]);

            }

        }

    }

    cout << dp[masca][k + 1];


    return 0;
}