#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(x) (x).begin(), (x).end()
#define md ((tl + tr) >> 1)
#define TL v + v, tl, md
#define TR v + v + 1, md + 1, tr
#define F first
#define S second
#define pii pair<int, int>
#define int ll
const int maxn = 1e6 + 7;
const ll inf = 1e18 + 7;
int n, m, a[maxn], d[2][maxn];
vector<int> g[maxn];
pii e[maxn];
void solve() {
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= m; i++) {
cin >> e[i].F >> e[i].S;
g[e[i].F].push_back(e[i].S);
g[e[i].S].push_back(e[i].F);
}
fill(d[0] + 1, d[0] + n + 1, inf);
fill(d[1] + 1, d[1] + n + 1, inf);
priority_queue<pii, vector<pii>, greater<pii>> q;
d[0][1] = 0;
q.push({0, 1});
while (!q.empty()) {
auto [D, v] = q.top();
q.pop();
if (D != d[0][v]) continue;
for (auto to : g[v]) {
if (max(d[0][v] + 1, a[to]) < d[0][to]) {
d[0][to] = max(d[0][v] + 1, a[to]);
q.push({d[0][to], to});
}
}
}
d[1][n] = 0;
q.push({0, n});
while (!q.empty()) {
auto [D, v] = q.top();
q.pop();
if (D != d[1][v]) continue;
for (auto to : g[v]) {
if (max(d[1][v] + 1, a[to]) < d[1][to]) {
d[1][to] = max(d[1][v] + 1, a[to]);
q.push({d[1][to], to});
}
}
}
int ans = inf;
for (int i = 1; i <= n; i++) {
ans = min(ans, d[0][i] + d[1][i] + abs(d[0][i] - d[1][i]));
}
for (int i = 1; i <= m; i++) {
if (d[0][e[i].F] >= a[e[i].S]) ans = min(ans, d[0][e[i].F] + d[1][e[i].S] + abs(d[0][e[i].F] - d[1][e[i].S]) + 1);
swap(e[i].F, e[i].S);
if (d[0][e[i].F] >= a[e[i].S]) ans = min(ans, d[0][e[i].F] + d[1][e[i].S] + abs(d[0][e[i].F] - d[1][e[i].S]) + 1);
}
cout << ans;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int test = 1;
// cin >> test;
while (test--) {
solve();
// cout << '\n';
}
return 0;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |