设 在 中的位置为 ,那么 中 合法当且仅当 。
那么很显然对于 ,设 为最小的 满足 合法, 肯定是单调不减的。
所以只用双指针维护一下 即可。
code
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=1e6+5;
int n,a[N],b[N];
int pos[N],ans;
signed main(){
ios::sync_with_stdio(0),cin.tie(0);
cin>>n;for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++) cin>>b[i];
for(int i=1;i<=n;i++) pos[b[i]]=i;
int l=1,lst=pos[a[1]];
for(int i=1;i<=n;i++){
if(pos[a[i]]<lst) l=i;
lst=pos[a[i]];ans+=i-l+1;
}
cout<<ans;
return 0;
}