#include<bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
#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];
int a[mxn];
ll dst[2][mxn]{0};
bool vis[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;
priority_queue<pii,vector<pii>,greater<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++){
//cout<<vec[i].f<<' '<<vec[i].s<<' '<<dst[x][vec[i].s]<<'\n';
if(mem==vec[i].f&&dst[x][vec[i].s]!=2e16){
int v=vec[i].s;pq.push({dst[x][v],v});
}
else if(vec[i].f!=mem){
//cout<<mem<<' ';
while(!pq.empty()){
auto uu=pq.top();pq.pop();
//cout<<uu.s<<' ';
if(vis[uu.s])continue;
vis[uu.s]=1;
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});
}
}
}mem=vec[i].f;int v=vec[i].s;
if(dst[x][v]!=2e16)pq.push({dst[x][v],v});
//cout<<'\n';
}
}//cout<<mem<<' ';
while(!pq.empty()){
auto uu=pq.top();pq.pop();
//cout<<uu.s<<' ';
if(vis[uu.s])continue;
vis[uu.s]=1;
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});
}
}
}
memset(vis,0,sizeof vis);
}
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=2;i<=n-1;i++)rs=min(rs,dst[0][i]+dst[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... |