题解 | #分层图最短路#
分层图最短路
https://ac.nowcoder.com/acm/problem/236176
如果直接按照分层图最短路DP做法来搞的话,数组需要开成 dist[N][N], st[N][N], N是1e5级别的,明显会爆空间,那就直接给每两层之间的任意两点连一条边权为C的边,然后跑一遍最短路就好了。
代码(写的比较丑)
#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 100010, M = 20000010, inf = 0x3f3f3f3f;
#define x first
#define y second
typedef pair<int,int> PII;
int h[maxn], e[M], w[M], ne[M], idx;
bool st[maxn];
vector<int> v[maxn];
int dist[maxn];
int n, m, k;
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
void Dijkstra()
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, 1});
while(heap.size())
{
auto t = heap.top();
heap.pop();
int u = t.y;
if(st[u]) continue;
st[u] = true;
for(int i = h[u]; i != -1; i = ne[i]){
int j = e[i];
if(dist[j] > dist[u] + w[i]){
dist[j] = dist[u] + w[i];
heap.push({dist[j], j});
}
}
}
}
int main()
{
memset(h, -1, sizeof h);
scanf("%d %d %d", &n, &m, &k);
int max_depth = 0;
for(int i = 1; i <= n; i ++){
int x; scanf("%d", &x);
v[x].push_back(i);
max_depth = max(max_depth, x);
}
for(int i = 0; i < m; i ++){
int a, b, c; scanf("%d %d %d", &a, &b, &c);
add(a, b, c); add(b, a, c);
}
for(int i = 1; i < max_depth; i ++){
auto t1 = v[i], t2 = v[i + 1];
for(int j = 0; j < t1.size(); j ++){
for(int p = 0; p < t2.size(); p ++){
add(t1[j], t2[p], k);
add(t2[p], t1[j], k);
}
}
}
Dijkstra();
if(dist[n] >= inf / 2) puts("-1");
else printf("%d\n", dist[n]);
}