题解
考虑一个事实,我们只会单调不降地走到这条路上 最大的那个点,再单调不增地走到终点。那么我们枚举这个最大值在哪里出现,那么显然只有 大于等于前面走过的所有值时才是一个可能的答案。
对于一个点来说,走到这里的花费为 。如果 时,我们就要在前面的路上一边上升一边往前走,再在 上升到 ,那么花费就是 。反之前面的距离已经足够我们升到这么高了,直接从 走过来也就是 。于是从 和 分别跑一遍再拼起来就行。
AC_Code
#include<bits/stdc++.h>
using namespace std;
#define PII pair<long long, long long>
#define xx first
#define yy second
#define int long long
const int N = 2e5 + 10;
int n, m, a[N], ans = 1e18, d1[N], d2[N], INF = 1e14, h1[N], h2[N], mi;
bool vis[N];
vector<int> G[N];
struct node{
int dis, high, id;
bool operator < (const node b)const{
return dis > b.dis;
}
};
void dij(int *dis, int *h, int x){
priority_queue<node> q;
for(int i = 1; i <= n; i ++)dis[i] = h[i] = INF, vis[i] = 0;
q.push({0, 0, x});
dis[x] = 0, h[x] = 0;
while(!q.empty()){
auto u = q.top();
q.pop();
if(vis[u.id])continue;
vis[u.id] = 1;
for(auto i : G[u.id]){
if(vis[i])continue;
if(dis[i] > dis[u.id] + 1){
dis[i] = max(a[i], dis[u.id] + 1);
if(a[i] >= u.high)h[i] = dis[i];
q.push({dis[i], max(u.high, a[i]), i});
}
}
}
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n >> m;
for(int i = 1; i <= n; i ++){
cin >> a[i];
}
for(int i = 1; i <= m; i ++){
int x, y;
cin >> x >> y;
G[x].push_back(y);
G[y].push_back(x);
}
dij(d1, h1, 1);
dij(d2, h2, n);
for(int i = 1; i <= n; i ++){
ans = min(ans, h1[i] + h2[i]);
}
cout << ans;
return 0;
}完结撒花。