题解:AT_abc439_e [ABC439E] Kite

· · 题解

题目分析

题目要求在 N 条连接 (A_i, 0) 和 (B_i, 1) 的线段中,选出最多的线段,使得它们互不相交(包括端点)。

解题思路

这道题其实就是求两个数组的最长上升子序列 (LIS) 。
我们利用 sort 对结构体排序,随后使用贪心+二分(lower_bound)的方法在 O(N \log N) 的时间内求出 B 数组的最长上升子序列长度。

参考代码

#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+5;
int n,dp[maxn];
int low[maxn],len=1;
struct node{
    int x,y;
}a[maxn];
bool cmp(node x,node y){
    if(x.x==y.x){
        return x.y>y.y;
    }
    return x.x<y.x;
}

int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i].x>>a[i].y;
        dp[i]=1;
    }
    sort(a+1,a+n+1,cmp);
    low[1]=a[1].y;
    for(int i=1;i<=n;i++){
        if(a[i].y>low[len]){
            low[++len]=a[i].y;
        }
        else{
            low[lower_bound(low+1,low+len+1,a[i].y)-low]=a[i].y;
        }
    }
    cout<<len;
    return 0;
}