牛客,似花还似非花(dp优化)

似花还似非花
这个题实际上是求解两个排列的包含某一特定元素的情况下的最长公共子序列长度。
最长上升子序列用树状数组优化

//#pragma GCC optimize(2)
//#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
#define int long long
#define fi first
#define se second
#define pb push_back
#define pii pair<int,int>
#define yes cout<<"Yes\n"
#define no cout<<"No\n"
#define yesno if(fg)yes;else no;
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
const int inf=8e18;
const int maxn=2e5+100;
int a[maxn],b[maxn],c[maxn],c2[maxn],pos[maxn];
int dp[maxn],dp2[maxn];
int lowbit(int x)
{
	return x&(-x);
}
void update(int x,int val)
{
	while(x<maxn)
	{
		c[x]=max(c[x],val);
		x+=lowbit(x);
	}
}
void update2(int x,int val)
{
	while(x>0)
	{
		c2[x]=max(c2[x],val);
		x-=lowbit(x);
	}
}
int ask(int x)
{
	int ans=0;
	while(x>0)
	{
		ans=max(ans,c[x]);
		x-=lowbit(x);
	}
	return ans;
}
int ask2(int x)
{
	int ans=0;
	while(x<maxn)
	{
		ans=max(ans,c2[x]);
		x+=lowbit(x);
	}
	return ans;
}
signed main()
{
	IOS
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		int x;
		cin>>x;
		pos[x]=i;
	}
	for(int i=1;i<=n;i++)
	{
		int x;
		cin>>x;
		a[i]=pos[x];
		b[x]=i;
	}
	for(int i=1;i<=n;i++)
	{
		dp[i]=ask(a[i])+1;
		update(a[i],dp[i]);
	}
	for(int i=n;i>=1;i--)
	{
		dp2[i]=ask2(a[i])+1;
		update2(a[i],dp2[i]);
	}

	int q;
	cin>>q;
	while(q--)
	{
		int x;
		cin>>x;
		x=b[x];
		cout<<n-dp[x]-dp2[x]+1<<"\n";
	}
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

thusloop

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值