题目传送门//res tp nowcoder
分析
定理:B1~B2当且仅当B1与B2有同构的笛卡尔树。 (B₁~B₂ iff B₁ and B₂ have isomorphic Cartesian trees.)
对A与B同时构建小根堆性笛卡尔树,每次同时插入结点时,判断是否同构即可.
#include<iostream>
#include<cstdio>
using namespace std;
const int L = 100010;
int a[L],b[L],u[L],v[L];
int n;
void build(){
u[n + 1] = v[n + 1] + 1;
int i;
for(i = 2;i<=n;++i){
int k1 = i-1,k2 = i-1;
while(a[i] < a[k1]) k1 = u[k1];
while(b[i] < b[k2]) k2 = v[k2];
if(k1!=k2){
printf("%d
",i-1);break;
}
u[i] = k1;v[i] = k2;
}
if(i == n+1) printf("%d
",n);
}
int main(){
while(scanf(" %d",&n)!=EOF){
for(int i = 1;i <= n;++i){
scanf(" %d",&a[i]);u[i]=0;
}
for(int i = 1;i <= n;++i){
scanf(" %d",&b[i]);v[i]=0;
}
build();
}
return 0;
}