【题解】P3489 WIE-Hexer

题目传送门

前言

感觉和孤岛营救问题完全一致,建图好像还更简单一点。

前置芝士

最短路,状压

分析

看到 \(p\) 很小我们考虑状态压缩,设 \(d[u][s]\) 表示走到点 \(u\) 时剑的状态为 \(s\) 时的最短路,然后我们考虑怎么在跑最短路是转移,首先,如果当前节点有宝剑,那么我们把宝剑捡起来肯定不会更劣,所以我们可以用当前最短路去更新捡到钥匙后的状态的最短路,然后就是照常按 dijkstra 转移即可,注意要判断现有钥匙能否经过当前道路。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <bits/stdc++.h>
#define pii pair<int, pair<int, int> >
#define mk(a, b) make_pair(a, b)

using namespace std;
const int N = 210, M = 6010, K = 1 << 15;
int h[N], e[M], ne[M], w[M], s[N], idx;
int st[N];
int d[N][K], vis[N][K];
int n, m, p, k;

inline int read()
{
int x = 0, y = 1; char c = getchar();
while (c < '0' || c > '9') {if (c == '-') y = -1; c = getchar();}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * y;
}

inline void add(int a, int b, int c, int d)
{
e[idx] = b;
w[idx] = c;
s[idx] = d;
ne[idx] = h[a];
h[a] = idx++;
}

inline bool check(int st1, int st2)
{
for (int i = 14; i >= 0; i--)
if ((st2 >> i & 1) && !(st1 >> i & 1))
return false;
return true;
}

inline void dijkstra()
{
memset(d, 0x3f, sizeof d);
d[1][0] = 0;
priority_queue<pii, vector<pii>, greater<pii> > q;
q.push(mk(0, mk(1, 0)));
while (q.size())
{
pii t = q.top();
q.pop();
int u = t.second.first, stt = t.second.second;
if (vis[u][stt]) continue;
vis[u][stt] = true;
if (st[u])
{
int sta = stt | st[u];
if (d[u][sta] > d[u][stt])
{
d[u][sta] = d[u][stt];
q.push(mk(d[u][sta], mk(u, sta)));
}
}
for (int i = h[u]; ~i; i = ne[i])
{
int v = e[i];
if (s[i] && !check(stt, s[i])) continue;
if (d[v][stt] > d[u][stt] + w[i])
{
d[v][stt] = d[u][stt] + w[i];
q.push(mk(d[v][stt], mk(v, stt)));
}
}
}
}

int main()
{
memset(h, -1, sizeof h);
n = read(), m = read(), p = read(), k = read();
while (k--)
{
int u = read(), x = read();
while (x--)
{
int y = read();
st[u] |= 1 << y;
}
}
while (m--)
{
int a = read(), b = read(), c = read(), x = read();
int tmp = 0;
while (x--)
{
int y = read();
tmp |= 1 << y;
}
add(a, b, c, tmp);
add(b, a, c, tmp);
}
dijkstra();
int res = 0x3f3f3f3f;
for (int i = 0; i < 1 << (p + 1); i++)
res = min(res, d[n][i]);
if (res == 0x3f3f3f3f) puts("-1");
else printf("%d\n", res);
return 0;
}