2019 牛客多校第四场 J - free

分层最短路,这题需要处理重边和自环,处理方法是自环不添加到图中,重边只算最短的。

相关题:BZOJ 2763,计蒜客 A1958 [TODO: add links]

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
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
template <typename Int>
void getInt(Int &x) {
x = 0; char ch = getchar(); Int sgn = 1;
while (ch < '0' || ch > '9') { if (ch == '-') sgn = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); }
x *= sgn;
}
const LL MAX_N = 1000 + 5;
const LL MAX_K = 10 + 5;
struct Edge {
LL from, to, cost;
Edge(LL from_ = 0, LL to_ = 0, LL cost_ = 0)
: from(from_), to(to_), cost(cost_) {}
};
vector <Edge> g[MAX_N];
LL n, m, k, s, t;
struct Node {
LL val, id, used;
Node(LL val_ = 0, LL id_ = 0, LL used_ = 0)
: val(val_), id(id_), used(used_) {}
friend bool operator > (const Node &x, const Node &y) {
return x.val > y.val;
}
};
priority_queue < Node, vector <Node>, greater <Node> > q;
LL d[MAX_N][MAX_K];
map < pair <LL, LL>, LL> mp;
int main() {
getInt(n), getInt(m), getInt(s), getInt(t), getInt(k);
LL u, v, w;
for (LL i = 1; i <= m; ++i) {
getInt(u), getInt(v), getInt(w);
if (u == v) continue;
else if (mp.find({u, v}) != mp.end()) mp[{u, v}] = min(mp[{u, v}], w);
else if (mp.find({v, u}) != mp.end()) mp[{v, u}] = min(mp[{v, u}], w);
else mp[{u, v}] = w;
}
for (auto const &e: mp) {
u = e.first.first; v = e.first.second; w = e.second;
g[u].push_back(Edge(u, v, w));
g[v].push_back(Edge(v, u, w));
}
for (LL i = 0; i < MAX_N; ++i) {
for (LL j = 0; j < MAX_K; ++j) {
d[i][j] = INT_MAX;
}
}
d[s][0] = 0;
q.push(Node(0, s, 0));
while (!q.empty()) {
Node x = q.top(); q.pop();
for (unsigned i = 0; i < g[x.id].size(); ++i) {
Edge &e = g[x.id][i];
// pay
if (x.val + e.cost < d[e.to][x.used]) {
d[e.to][x.used] = x.val + e.cost;
q.push(Node(d[e.to][x.used], e.to, x.used));
}
// else
if (x.used < k && x.val + 0 < d[e.to][x.used + 1]) {
d[e.to][x.used + 1] = x.val + 0;
q.push(Node(d[e.to][x.used + 1], e.to, x.used + 1));
}
}
}
LL ans = INT_MAX;
for (LL i = 0; i <= k; ++i) ans = min(ans, d[t][i]);
printf("%lld\n", ans);
return 0;
}