luogu U39019 迷宫

题目描述

https://www.luogu.com.cn/problem/U39019

Solution

我们考虑 $dijkstra$ 求最短路的过程

其中 $dis[v]$ 是由最小的 $dis[u]+w$ 转移过来的,那么现在我们有 $d$ 条边被限制

所有 $dis[v]$ 应由第 $d+1$ 小的 $dis[u]+w$ 转移

时间复杂度 $O(m\log m\log d)$

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
#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#define maxn 100010
#define maxm 1000010
#define INF 1000000000
using namespace std;

int n, m, k, d;

struct Edge {
int to, next, w;
} e[maxm * 2]; int c1, head[maxn];
inline void add_edge(int u, int v, int w) {
e[c1].to = v; e[c1].w = w;
e[c1].next = head[u]; head[u] = c1++;
}

struct Queue {
int k, d;

friend bool operator < (const Queue &u, const Queue &v) { return u.d > v.d; }
};

int dis[maxn]; bool vis[maxn], ext[maxn];
priority_queue<int> S[maxn];
void dijkstra() {
priority_queue<Queue> Q;
for (int i = 1; i <= n; ++i) {
dis[i] = ext[i] ? 0 : INF;
if (ext[i]) Q.push({ i, 0 });
}
for (int i = 1; i <= n; ++i) vis[i] = 0;
while (!Q.empty()) {
int u = Q.top().k; Q.pop();
if (vis[u]) continue; vis[u] = 1;
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i].w;
if (dis[v] > dis[u] + w) {
S[v].push(dis[u] + w);
if (S[v].size() > d) S[v].pop();
if (S[v].size() == d) dis[v] = S[v].top(), Q.push({ v, dis[v] });
}
}
}
}

int main() { fill(head, head + maxn, -1);
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

cin >> n >> m >> k >> d; ++d;
for (int i = 1; i <= m; ++i) {
int x, y, z; cin >> x >> y >> z; ++x; ++y;
add_edge(x, y, z); add_edge(y, x, z);
}
for (int i = 1, x; i <= k; ++i) cin >> x, ++x, ext[x] = 1;
dijkstra(); cout << (dis[1] == INF ? -1 : dis[1]) << "\n";
return 0;
}