Cod sursa(job #2126991)

Utilizator andreigasparoviciAndrei Gasparovici andreigasparovici Data 10 februarie 2018 11:08:45
Problema Ubuntzei Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.62 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 2005;
const int INF = 0x3f3f3f3f;
const int KMAX = 16;

int n, m, k;
int c[NMAX], cost[NMAX][NMAX], d[NMAX], dp[1 << KMAX][KMAX];
vector<pair<int, int>> g[NMAX];

void read() {
  scanf("%d %d %d ", &n, &m, &k);

  for (int i = 0; i < k; i++)
    scanf("%d ", &c[i]);

  c[k++] = n;

  for (int i = 1; i <= m; i++) {
    int x, y, c;
    scanf("%d %d %d ", &x, &y, &c);
    g[x].push_back({y, c});
    g[y].push_back({x, c});
  }
}

void bellman(int x) {
  fill(d + 1, d + n + 1, INF);
  d[x] = 0;

  queue<int> q;
  q.push(x);

  while (!q.empty()) {
    x = q.front();
    q.pop();
    for (auto& y : g[x]) {
      if (d[y.first] > d[x] + y.second) {
        d[y.first] = d[x] + y.second;
        q.push(y.first);
      }
    }
  }
}

void costs() {
  for (int i = 0; i < k; i++) {
    bellman(c[i]);
    for (int j = 0; j <= n; j++)
      cost[i][j] = d[j];
  }
}

void init() {
  for (int i = 0; i < (1 << k); i++)
    for (int j = 0; j < k; j++)
      dp[i][j] = INF;

  for (int i = 0; i < k; i++)
    dp[1 << i][i] = cost[i][1];
}

void hamilton(int drum) {
  for (int nod = 0; nod < k; nod++) {
    if (drum & (1 << nod)) {
      for (int vecin = 0; vecin < k; vecin++) {
        if (drum & (1 << vecin)) {
          dp[drum][nod] = min(dp[drum][nod], dp[drum ^ (1 << nod)][vecin] + cost[vecin][c[nod]]);
        }
      }
    }
  }
}

int main() {
  freopen("ubuntzei.in", "r", stdin);
  freopen("ubuntzei.out", "w", stdout);

  read();
  costs();
  init();

  for (int drum = 1; drum < (1 << k); drum++)
    hamilton(drum);

  printf("%d\n", dp[(1 << k) - 1][k - 1]);

  return 0;
}