[BZOJ1579] [Usaco2009 Feb]Revamping Trails 道路升级(分层图最短路 + 堆优化dijk)
dis[i][j]表示第i个点,更新了j次的最短路
此题不良心,卡spfa
#include <queue> #include <cstdio> #include <cstring> #include <iostream> #define N 50001 using namespace std; struct node { int a, b, c; node(int a, int b, int c) : a(a), b(b), c(c) {} bool operator > (const node& gg) const { return a > gg.a; } }; int n, m, k, cnt; int head[N], to[N << 1], next[N << 1], val[N << 1], dis[N][21]; bool vis[N][21]; priority_queue <node, vector <node>, greater <node> > q; inline int read() { int x = 0, f = 1; char ch = getchar(); for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1; for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0'; return x * f; } inline void add(int x, int y, int z) { to[cnt] = y; val[cnt] = z; next[cnt] = head[x]; head[x] = cnt++; } inline void dijkstra() { int i, u, v, x; memset(dis, 127, sizeof(dis)); q.push(node(0, 1, 0)); dis[1][0] = 0; while(!q.empty()) { u = q.top().b; x = q.top().c; q.pop(); if(vis[u][x]) continue; vis[u][x] = 1; for(i = head[u]; i ^ -1; i = next[i]) { v = to[i]; if(dis[v][x] > dis[u][x] + val[i]) { dis[v][x] = dis[u][x] + val[i]; q.push(node(dis[v][x], v, x)); } if(x + 1 <= k && dis[v][x + 1] > dis[u][x]) { dis[v][x + 1] = dis[u][x]; q.push(node(dis[v][x + 1], v, x + 1)); } } } } int main() { int i, x, y, z; n = read(); m = read(); k = read(); memset(head, -1, sizeof(head)); for(i = 1; i <= m; i++) { x = read(); y = read(); z = read(); add(x, y, z); add(y, x, z); } dijkstra(); printf("%d\n", dis[n][k]); return 0; }