#include<bits/stdc++.h>
#define ll long long
#define pii pair<ll,ll>
#define pll pair<ll,ll>
#define plx pair<ll,int>
#define f first
#define s second
#define pb push_back
#define all(x) x.begin(),x.end()
#define szz(r) (ll)r.size()
#define vi vector<int>
#define vvi vector<vi>
#define pp pair<ll,int>
#define ub(x,i) upper_bound(all(x),i)-x.begin()
using namespace std;
const int mxn=2e5+5;
vector<int>g[mxn];
ll a[mxn];
ll dst[2][mxn]{0};
ll dd[2][mxn]{0};
bool vis[mxn]{0};
bool can[2][mxn]{0};
void solve(int u,int x,int n){
vector<pii>vec;
for(int i=1;i<=n;i++)vec.pb({a[i],i});
sort(all(vec));
int mem=vec[0].f;
queue<pii>pq;
for(int i=1;i<=n;i++)dst[x][i]=2e16;dst[x][u]=0;
for(int i=0;i<vec.size();i++){
if(mem==vec[i].f&&dst[x][vec[i].s]!=2e16){
int v=vec[i].s;pq.push({dst[x][v],v});
can[x][v]=1;
dd[x][v]=dst[x][v];
}
else {
while(!pq.empty()){
auto uu=pq.front();pq.pop();
for(auto v:g[uu.s]){
if(dst[x][v]>max(a[v],uu.f+1)){
dst[x][v]=max(a[v],uu.f+1);
if(a[v]<mem)pq.push({dst[x][v],v});
if(a[v]==mem){
pq.push({dst[x][v],v});can[x][v]=1;dd[x][v]=dst[x][v];
}
}
}
}mem=vec[i].f;int v=vec[i].s;
if(dst[x][v]!=2e16)pq.push({dst[x][v],v}),can[x][v]=1,dd[x][v]=dst[x][v];
}
}
while(!pq.empty()){
auto uu=pq.front();pq.pop();
for(auto v:g[uu.s]){
if(dst[x][v]>max(a[v],uu.f+1)){
dst[x][v]=max(a[v],uu.f+1);
if(a[v]<mem)pq.push({dst[x][v],v});
if(a[v]==mem){
pq.push({dst[x][v],v});can[x][v]=1;dd[x][v]=dst[x][v];
}
}
}
}
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);
int n,m;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].pb(y);g[y].pb(x);
}
solve(1,0,n);
solve(n,1,n);
ll rs=2e16;
for(int i=1;i<=n;i++)if(can[0][i]&&can[1][i])rs=min(rs,dd[0][i]+dd[1][i]);
cout<<rs;
}
# | 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... |