题解:P13788 「CZOI-R6」Permutation and Subsequence

· · 题解

marp:true

题意

统计排列 a 的非空连续子段中,有多少个是排列 b 的子序列。

分析

我们需要证明:a 的连续子段 a_i,a_{i+1},\dots,a_j 是 b 的子序列,当且仅当该子段在 b 中的位置构成严格递增序列。

  1. 必要性

若 a_i,a_{i+1},\dots,a_j 是 b 的子序列,则根据子序列定义,存在 b 中的位置序列 k_i<k_{i+1}<\dots<k_j,使得 b_{k_m}=a_m(其中 i\leq m\leq j)。

由于 pos_x 表示 x 在 b 中的位置(即 pos_{a_m}=k_m),因此 pos_{a_i}<pos_{a_{i+1}}<\dots<pos_{a_j},即位置序列严格递增。

  1. 充分性

若 a_i,a_{i+1},\dots,a_j 在 b 中的位置序列严格递增(即 pos_{a_i}<pos_{a_{i+1}}<\dots<pos_{a_j}),则在 b 中取这些位置对应的元素,恰好是 a_i,a_{i+1},\dots,a_j,且顺序与 b 中一致。 根据子序列定义,a_i,a_{i+1},\dots,a_j 是 b 的子序列。

注意,pos 是元素到固定位置的映射,而 k 是动态的子序列位置。

综上,问题可转化为:统计数组 c 中所有非空连续严格递增子段的数量,其中 c_i=pos_{a_i}(即 a 中元素在 b 中的位置)。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1000005;
int a[maxn],b[maxn],n,pos[maxn],c[maxn];
int main() {
    scanf("%d",&n);
    for(int i=1;i<=n;++i) scanf("%d",a+i);
    for(int i=1;i<=n;++i) scanf("%d",b+i),pos[b[i]]=i;
    for(int i=1;i<=n;++i) c[i]=pos[a[i]];
    ll sum=1;
    int cnt=1;
    for(int i=2;i<=n;++i){
        if(c[i]>c[i-1]) ++cnt;
        else cnt=1;
        sum+=cnt;
    }
    printf("%lld",sum);
}