跳到正文

题解

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

xu_zhihao约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
P13788

版本

  1. v1当前

注意到输入的 a,ba,b 是 1∼n1 \sim n 的排列,这说明不论 aa 或 bb 都没有重复出现的数字。

我们可以初始化 wbi=iw_{b_i}=i,然后遍历 aa 数组。用一个栈来记录信息,最后一个入栈的元素记为 toptop,然后分三类讨论。

  1. wtop<waiw_{top} < w_{a_i}。可以看成栈内的元素从栈底到栈顶可以看成是序列 aa 的一个子串,这个子串记为 nn,那么对于每一个 2≤i≤∣n∣2 \le i \le \lvert n \rvert 有 wni−1<wniw_{n_{i-1}} < w_{n_i},在子串末尾加入 aia_i 性质不变。故直接把 aia_i 加入栈顶。

  2. wtop>waiw_{top} >w_{a_i}。说明加入 aia_i 后上述的性质有变,而已在栈内的所有元素符合性质,所以对于 nn 的每一个子串(非空)都能在 bib_i 中找到一个与其相匹配的子序列。将栈内元素个数记为 ll,则栈内所有元素对答案的贡献为 l(l+1)2\frac{l(l+1)}{2}。之后即可清空栈并加入 aia_i 元素。

  3. 栈为空。同分讨 11,直接将 aia_i 加入栈顶即可。

AC 代码

C++
#include<bits/stdc++.h>
using namespace std;
int w[1000010];
int a[1000010];
int b[1000010];
int main(){
	int n;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	for(int i=1;i<=n;i++){
		cin>>b[i];
		w[b[i]]=i;
	}
	stack<int>q;
	long long ans=0;
	for(int i=1;i<=n;i++){
		if(!q.empty() && w[q.top()]>w[a[i]]){
			long long l=q.size();
			ans+=l*(l+1)/2;
			while(!q.empty())q.pop();
		}
		q.push(a[i]);
	}
	long long l=q.size();
	ans+=l*(l+1)/2;
	cout<<ans<<endl;
	return 0;
}
原文