Cod sursa(job #2374308)

Utilizator cella.florescuCella Florescu cella.florescu Data 7 martie 2019 17:54:47
Problema Ubuntzei Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.93 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 2e3;
const int MAXK = 15;
const int INF = 0x3f3f3f3f;

struct PQNode {
  int node, conf, cost;
  bool operator < (const PQNode& other) const {
    return cost > other.cost;
  }
};

int dp[MAXK + 2][1 << MAXK], ubu[MAXK + 2], dist[MAXN + 1];
vector < pair < int, int > > g[MAXN + 1], newg[MAXK + 2];
priority_queue < PQNode > pq;

inline void update(int node, int conf, int cost) {
  if (cost < dp[node][conf]) {
    dp[node][conf] = cost;
    pq.push({node, conf, cost});
  }
}

int main()
{
    int n, m, k;
    ifstream fin("ubuntzei.in");
    fin >> n >> m >> k;
    for (int i = 0; i < k; ++i)
      fin >> ubu[i];
    for (int i = 0; i < m; ++i) {
      int x, y, z;
      fin >> x >> y >> z;
      g[x].push_back({y, z});
      g[y].push_back({x, z});
    }
    fin.close();
    ubu[k] = 1;
    ubu[k + 1] = n;
    for (int i = 0; i < k + 2; ++i) {
      memset(dist, INF, sizeof dist);
      dist[ubu[i]] = 0;
      pq.push({ubu[i], 0, 0});
      while (pq.empty() == false) {
        int node = pq.top().node, cost = pq.top().cost;
        pq.pop();
        if (cost == dist[node])
          for (auto it : g[node])
            if (cost + it.second < dist[it.first]) {
              dist[it.first] = cost + it.second;
              pq.push({it.first, 0, dist[it.first]});
            }
      }
      for (int j = 0; j < k + 2; ++j)
        newg[i].push_back({j, dist[ubu[j]]});
    }
    memset(dp, INF, sizeof dp);
    dp[k][0] = 0;
    pq.push({k, 0, 0});
    while (pq.empty() == false) {
      int node = pq.top().node, cost = pq.top().cost, conf = pq.top().conf;
      pq.pop();
      if (dp[node][conf] == cost) {
        if (node < k)
          update(node, conf | (1 << node), cost);
        for (auto it : newg[node])
          update(it.first, conf, cost + it.second);
      }
    }
    ofstream fout("ubuntzei.out");
    fout << dp[k + 1][(1 << k) - 1] << '\n';
    fout.close();
    return 0;
}