Cod sursa(job #2856169)

Utilizator rapidu36Victor Manz rapidu36 Data 23 februarie 2022 15:19:15
Problema Ubuntzei Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.24 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>

using namespace std;

const int N = 2000;
const int K = 15;
const int INF = 1e9;

int c[K+2][K+2], d[1 << (K + 2)][K], n, m, k, p[K+2], np, poz[N+1], dist[N+1];
vector <pair<int, int>> a[N+1];

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


void dijkstra(int x0)
{
    for (int i = 1; i <= n; i++)
    {
        dist[i] = INF;
    }
    dist[x0] = 0;
    bitset <N + 1> selectat;
    priority_queue <pair<int, int>> h;
    h.push({0, x0});
    while (!h.empty())
    {
        int x = h.top().second;
        h.pop();
        if (selectat[x])
        {
            continue;
        }
        selectat[x] = 1;
        for (auto p: a[x])
        {
            int y = p.first;
            int c = p.second;
            if (dist[x] + c < dist[y])
            {
                dist[y] = dist[x] + c;
                h.push({-dist[y], y});
            }
        }
    }

    int p_x0 = poz[x0];
    for (int i = 0; i < np; i++)
    {
        c[p_x0][i] = c[i][p_x0] = dist[p[i]];
    }
}

int drum_hamiltonian()
{
    for (int i = 0; i < (1 << np); i++)
    {
        for (int j = 0; j < np; j++)
        {
            d[i][j] = INF;
        }
    }
    d[1][0] = 0;
    for (int i = 1; i < (1 << np); i += 2)
    {
        for (int j = 0; j < np; j++)
        {
            if ((i & (1 << j)) && d[i][j] != INF)
            {
                for (int k = 0; k < np; k++)
                {
                    int ik = (i | (1 << k));
                    d[ik][k] = min(d[ik][k], d[i][j] + c[j][k]);
                }
            }
        }
    }
    return d[(1 << np) - 1][np - 1];
}

int main()
{
    in >> n >> m >> k;
    p[np++] = 1;
    poz[1] = 0;
    for (int i = 0; i < k; i++)
    {
        in >> p[np++];
        poz[p[np - 1]] = np - 1;
    }
    p[np++] = n;
    poz[n] = np - 1;
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;
        a[x].push_back({y, c});
        a[y].push_back({x, c});
    }
    in.close();
    for (int i = 0; i < np; i++)
    {
        dijkstra(p[i]);
    }
    out << drum_hamiltonian();
    out.close();
    return 0;
}