Portal: https://ac.nowcoder.com/acm/contest/881/A
Meaning: given two arrays a and b, find the maximum p, and satisfy that the subscripts of the minimum values of two arrays in any interval [1,p] are equal.
Idea: first, use monotone stack to run out the position of the first smaller number on the left and the first smaller number on the right of each element in arrays a and b. add 1 to the subscript on the left and subtract 1 from the subscript on the right. Then we get the minimum value interval of each number with this number as the interval.
Then, we traverse the interval of each number of two arrays. For an array with a total length of n, start from the first to compare. If the left and right bounds of the two numbers are equal, continue. If the left interval is the same but the right interval is not the same, then the space area should be reduced at this time. Take the minimum value of the two as the new interval length to run again. If they are not the same, directly jump out of the cycle. In this way, the interval is reduced step by step.
AC Code:
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
const int inf = 0x3f3f3f3f;
int dir[8][2]={{1,0},{0,1},{1,1},{1,-1},{-1,1},{-1,-1},{0,-1},{-1,0}};
#define pi acos(-1)
#define ls rt<<1
#define rs rt<<1|1
#define me0(s) memset(s,0,sizeof(s))
#define me1(s) memset(s,1,sizeof(s))
#define mef(s) memset(s,-1,sizeof(s))
#define meinf(s) memset(s,inf,sizeof(s))
const int N=100005;
int la[N],ra[N],lb[N],rb[N],sta[N],stb[N],a[N],b[N];
inline int read() {
char c=getchar(); int x=0, f=1;
while(c<'0'|c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
return x*f;
}
ll q_pow(ll a,ll b,ll mod){
ll anss=1;
while(b){
if(b&1) anss=anss*a%mod;
a=a*a%mod;
b>>=1;
}
return anss;
}
ll q_mul(ll a,ll b,ll mod){
ll anss=0;
while(b){
if(b&1) anss=(anss+a)%mod;
a=(a+a)%mod;
b>>=1;
}
return anss;
}
int main(int argc, char * argv[]) {
std::ios::sync_with_stdio(false);
int n;
while(cin>>n){
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++) cin>>b[i];
int top1=0;
for(int i=1;i<=n;i++){
while(top1&&a[sta[top1-1]]>=a[i]){
top1--;
}
la[i]=(top1==0)?0:sta[top1-1];
sta[top1++]=i;
}
top1=0;
for(int i=n;i>=1;i--){
while(top1&&a[sta[top1-1]]>=a[i]) top1--;
ra[i]=(top1==0)?(n+1):sta[top1-1];
sta[top1++]=i;
}
int top2=0;
for(int i=1;i<=n;i++){
while(top2&&b[stb[top2-1]]>=b[i]){
top2--;
}
lb[i]=(top2==0)?0:stb[top2-1];
stb[top2++]=i;
}
top2=0;
for(int i=n;i>=1;i--){
while(top2&&b[stb[top2-1]]>=b[i]) top2--;
rb[i]=(top2==0)?(n+1):stb[top2-1];
stb[top2++]=i;
}
for(int i=1;i<=n;i++){
la[i]=la[i]+1;
ra[i]=ra[i]-1;
lb[i]=lb[i]+1;
rb[i]=rb[i]-1;
}
// for(int i=1;i<=n;i++){
// cout<<la[i]<<" "<<ra[i]<<" "<<lb[i]<<" "<<rb[i]<<endl;
// }
for(int i=1;i<=n;i++){
if(la[i]==lb[i]&&ra[i]==rb[i]){
continue;
}
else if(la[i]==lb[i]&&ra[i]!=rb[i])
n=min(ra[i],rb[i]);
else break;
}
cout<<n<<endl;
}
return 0;
}