Cod sursa(job #2842924)

Utilizator iancupoppPopp Iancu Alexandru iancupopp Data 1 februarie 2022 18:32:27
Problema Ubuntzei Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.85 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int N = 2e3 + 5;
const int K = 18;
const int INF = 1e9;

vector<pair<int, int>> gr[N];
int dp[1 << K][K], d[N], cost[K][K];

void dijkstra(int start) {
  priority_queue<pair<int, int>> pq;
  pq.push({0, start});
  while (!pq.empty()) {
    auto p = pq.top();
    pq.pop();
    int nod = p.second;
    int dist = -p.first;
    if (d[nod] < dist)
      continue;
    d[nod] = dist;
    for (auto e: gr[nod])
      if (dist + e.second < d[e.first]) {
        d[e.first] = dist + e.second;
        pq.push({-d[e.first], e.first});
      }
  }
}

int hamilton(int n) {
  for (int i = 0; i < (1 << n); ++i)
    for (int j = 0; j < n; ++j)
      dp[i][j] = INF;
  dp[1][0] = 0;
  for (int i = 0; i < (1 << n) - 1; ++i)
    for (int from = 0; from < n; ++from) {
      if ((i & (1 << from)) == 0)
        continue;
      for (int to = 0; to < n; ++to) {
        if ((i & (1 << to)) != 0)
          continue;
        dp[i | (1 << to)][to] = min(dp[i | (1 << to)][to], dp[i][from] + cost[from][to]);
      }
    }
  return dp[(1 << n) - 1][n - 1];
}

int main() {
  ifstream cin("ubuntzei.in");
  ofstream cout("ubuntzei.out");
  int n, m;
  cin >> n >> m;
  vector<int> v;
  v.push_back(1);
  int k;
  cin >> k;
  for (int i = 0; i < k; ++i) {
    int x;
    cin >> x;
    v.push_back(x);
  }
  v.push_back(n);
  k += 2;
  while (m--) {
    int x, y, c;
    cin >> x >> y >> c;
    gr[x].emplace_back(y, c);
    gr[y].emplace_back(x, c);
  }
  cin.close();
  for (int i = 0; i < k; ++i)
    for (int j = 0; j < k; ++j)
      cost[i][j] = INF;
  for (int i = 0; i < k - 1; ++i) {
    for (int j = 1; j <= n; ++j)
      d[j] = INF;
    dijkstra(v[i]);
    for (int j = 0; j < k; ++j) {
      if (j == i) continue;
      cost[i][j] = cost[j][i] = d[v[j]];
    }
  }
  cout << hamilton(k) << "\n";
  cout.close();
  return 0;
}