// Problem URL: https://oj.uz/problem/view/JOI23_ho_t4
// Start Time: 5/27/2025, 9:44:51 PM
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define mp make_pair
#define pb push_back
#define F first
#define S second
#define debug(x) std::cout << #x << ": " << x << "\n"
#define all(v) v.begin(), v.end()
#define li(i,a,b) for (int i = a; i < b; i++)
#define endl '\n'
#define mem(name,val) memset(name,val,sizeof(name))
#define max(a,b) max<ll>(a,b)
#define min(a,b) min<ll>(a,b)
const int nmax = 2e5+3;
vector<int> adj[nmax];
int p[nmax], pos[nmax];
int n;
bool obst[nmax]; // is there obstacle on node i
ll maxmoves(int mn){
if(obst[mn-1]==1 and obst[mn+1]==1)return 0; // base case
// nadji ili p[mn]-1 ili max node pre blokade
obst[mn]=1;
// levo
int l = mn;
for(int i = mn-1; i>0 && obst[i]==0; i--){
if(p[i]==p[mn]-1){
l=i;break;
}
else if(l==mn || p[i]>p[l]) l=i;
}
// desno
int r = mn;
for(int i = mn+1; i < n+1 && obst[i]==0; i++){
if(p[i]==p[mn]-1){
r=i;break;
}
else if(r==mn || p[i]>p[r]) r=i;
}
ll left = 0, right = 0;
if(l!=mn)
left = abs<ll>(mn-l) + maxmoves(l);
if(r!=mn)
right = abs<ll>(r-mn)+ maxmoves(r);
obst[mn]=0;
return max(left,right);
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
cin>>n;
li(i,1,n+1){
cin>>p[i];
pos[p[i]]=i;
}
li(i,0,n-1){
int a,b;
cin>>a>>b;
adj[a].pb(b);
adj[b].pb(a);
}
obst[0]=obst[n+1]=1;
cout<<maxmoves(pos[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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |