「USACO09FEB」改造路Revamping Trails
传送门
Luogu
解题思路
有点像这题,但是现在这道不能跑k遍SPFA了,会TLE。
那么我们就跑分层图最短路,然后就变成模板题了。
细节注意事项
- 别跑SPFA就好了。
参考代码
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <ctime>
#include <queue>
#define rg register
using namespace std;
template < class T > inline void read(T& s) {
s = 0; int f = 0; char c = getchar();
while (!isdigit(c)) f |= c == '-', c = getchar();
while (isdigit(c)) s = s * 10 + c - 48, c = getchar();
s = f ? -s : s;
}
typedef long long LL;
const int _ = 210002;
const int __ = 6100002;
int tot, head[_], nxt[__], ver[__], w[__];
inline void Add_edge(int u, int v, int d)
{ nxt[++tot] = head[u], head[u] = tot, ver[tot] = v, w[tot] = d; }
int n, m, k, vis[_]; LL dis[_];
inline int id(int u, int k) { return u + k * n; }
inline void Dijkstra() {
static priority_queue < pair < LL, int > > Q;
memset(dis + 1, 0x3f, sizeof (LL) * (n * (k + 1)));
dis[id(1, 0)] = 0, Q.push(make_pair(0, id(1, 0)));
while (!Q.empty()) {
int u = Q.top().second; Q.pop();
if (vis[u]) continue; vis[u] = 1;
for (rg int i = head[u]; i; i = nxt[i]) {
int v = ver[i];
if (dis[v] > dis[u] + w[i])
dis[v] = dis[u] + w[i], Q.push(make_pair(-dis[v], v));
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("cpp.in", "r", stdin);
freopen("cpp.out", "w", stdout);
#endif
read(n), read(m), read(k);
for (rg int u, v, d; m--; ) {
read(u), read(v), read(d);
Add_edge(u, v, d), Add_edge(v, u, d);
for (rg int i = 1; i <= k; ++i) {
Add_edge(id(u, i), id(v, i), d);
Add_edge(id(v, i), id(u, i), d);
Add_edge(id(u, i - 1), id(v, i), 0);
Add_edge(id(v, i - 1), id(u, i), 0);
}
}
Dijkstra();
LL ans = 1e18;
for (rg int i = 0; i <= k; ++i)
ans = min(ans, dis[id(n, i)]);
printf("%lld\n", ans);
return 0;
}
完结撒花 \(qwq\)