ABC393F 题解

· · 题解

思路

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

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

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

代码

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

#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;
}

本题代码

#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;
}