#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int N = 100000;
const int K = 5;
const long long INF = 0x3f3f3f3f3f3f3f3fLL;
int hh[N];
vector<pair<int, int>> ejw[N];
long long dd[N << K];
int pq[N << K], iq[(N << K) + 1], pq_cnt;
bool lt(int i, int j) {
return dd[i] < dd[j];
}
int p2(int p) {
return (p <<= 1) > pq_cnt ? 0 : p ^ (p < pq_cnt && lt(iq[p ^ 1], iq[p]));
}
void pq_up(int i) {
int j, p, q;
for (p = pq[i]; (q = p >> 1) && lt(i, j = iq[q]); p = q)
iq[pq[j] = p] = j;
iq[pq[i] = p] = i;
}
void pq_dn(int i) {
int j, p, q;
for (p = pq[i]; (q = p2(p)) && lt(j = iq[q], i); p = q)
iq[pq[j] = p] = j;
iq[pq[i] = p] = i;
}
void pq_add_last(int i) {
iq[pq[i] = ++pq_cnt] = i;
}
int pq_remove_first() {
int i = iq[1], j = iq[pq_cnt--];
if (i != j)
pq[j] = 1, pq_dn(j);
pq[i] = 0;
return i;
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(NULL);
int n, k, m; cin >> n >> k >> m;
for (int i = 0; i < n; i++)
hh[i] = -1;
for (int h = 0; h < k; h++) {
int i; cin >> i, i--;
hh[i] = h;
}
while (m--) {
int i, j, w; cin >> i >> j >> w, i--, j--;
ejw[i].push_back({ j, w });
ejw[j].push_back({ i, w });
}
for (int ib = 0; ib < n << k; ib++)
dd[ib] = INF;
for (int i = 0; i < n; i++) {
int ib = i << k ^ (hh[i] == -1 ? 0 : 1 << hh[i]);
dd[ib] = 0, pq_add_last(ib);
}
while (pq_cnt) {
int ib = pq_remove_first(), i = ib >> k, b = ib & (1 << k) - 1;
if (b == (1 << k) - 1) {
cout << dd[ib] << '\n';
return 0;
}
for (auto jw : ejw[i]) {
int j = jw.first, w = jw.second, jb = j << k ^ b;
long long d = dd[ib] + w;
if (dd[jb] > d) {
if (dd[jb] == INF)
pq_add_last(jb);
dd[jb] = d, pq_up(jb);
}
}
for (int c = 0; c < 1 << k; c++) {
int ib_ = i << k ^ (b | c);
long long d = dd[ib] + dd[i << k ^ c];
if (dd[ib_] > d) {
if (dd[ib_] == INF)
pq_add_last(ib_);
dd[ib_] = d, pq_up(ib_);
}
}
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |