跳到正文

题解

ABC393F 题解

chenxi2009约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年2月16日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

思路

一眼离线,先按 RR 给询问排序。你会发现由于求的是最长上升子序列(以下称 LIS),所以 LIS 中的每一个数都 ≤X\le X 本质上就是它的最后一个数字 ≤X\le X。

考虑我们使用 O(Nlog⁡N)O(N\log N) 算法求一个长度为 NN 的序列 AA 的 LIS 的过程,fif_i 记录着长度为 ii 的 LIS 最后一个数最小可能是多少。诶?那么这个询问不就是在要求找出最大的 ii 使得 fi≤Xf_i\le X 吗?我们知道 ff 是不降的,所以二分就行了。

离线处理,时间复杂度 O(Qlog⁡Q+(Q+N)log⁡N)O(Q\log Q+(Q+N)\log N)。

代码

纯净版求 LIS 代码(供参考)

C++
#include<bits/stdc++.h> 
using namespace std;
int n,a[300000],f[300000],ans;
int main(){
	memset(f,0x3f,sizeof(f)),f[0] = 0;
	scanf("%d",&n);
	for(int i = 1;i <= n;i ++) scanf("%d",&a[i]);
	for(int i = 1;i <= n;i ++){
		x = lower_bound(f + 1,f + n + 1,a[i]) - f - 1;//a_i 可以接在最长长 x 的序列后 
		f[x + 1] = min(f[x + 1],a[i]),ans = max(ans,x + 1);//接上后长度为 x+1 
	}
	printf("%d",ans);
	return 0;
}

本题代码

C++
#include<bits/stdc++.h> 
using namespace std;
struct node{
	int r,x,w;
	bool friend operator < (const node &a,const node &b){
		return a.r < b.r;
	}
};
int n,q,a[300000],ans[300000],it = 1,f[300000],x;
node qry[300000];
int main(){
	memset(f,0x3f,sizeof(f)),f[0] = 0;
	scanf("%d%d",&n,&q);
	for(int i = 1;i <= n;i ++) scanf("%d",&a[i]);
	for(int i = 1;i <= q;i ++) scanf("%d%d",&qry[i].r,&qry[i].x);
	for(int i = 1;i <= q;i ++) qry[i].w = i;
	sort(qry + 1,qry + q + 1);//按 R 排序 
	for(int i = 1;i <= n;i ++){
		x = lower_bound(f + 1,f + n + 1,a[i]) - f - 1; 
		f[x + 1] = min(f[x + 1],a[i]);//求 LIS 部分 
		while(qry[it].r == i){
			ans[qry[it].w] = upper_bound(f + 1,f + n + 1,qry[it].x) - f - 1;//二分找第一个 i 使 f_i<=X_it 
			it ++;
		}
	}
	for(int i = 1;i <= q;i ++) printf("%d\n",ans[i]);
	return 0;
}
原文