Leetcode354. 二维嵌套问题(转换成一维的LIS)

题意:
给定 n n n组长为 a i a_i ai,宽为 b i b_i bi的红包,如果 a i < a j a_i<a_j ai<aj b i < b j b_i<b_j bi<bj,则红包 i i i可以装到红包 j j j中。现在问你一次最多可以嵌套多少个红包。
数据范围: 1 ≤ n ≤ 1 0 5 , 1 ≤ a i , b i ≤ 1 0 9 1\leq n\leq 10^5,1\leq a_i,b_i\leq 10^9 1n105,1ai,bi109

题解:
考虑升序排序第一维 a a a,然后对第二维 b b b做一遍LIS。这里的问题就是可能存在同 a a a的红包相互嵌套,这是不符合要求的,所以我们对第二维 b b b降序排序,保证每一维 a a a最多只会被选一个。

代码:

const int N = 100010;
struct Node {
    
    
    int w, h;
    bool operator < (const Node &A) const {
    
    
        if(w == A.w) return h > A.h;
        return w < A.w;
    }
}a[N];
int t[N], tg;

int b_s(int l, int r, int x) {
    
    
    while(l < r) {
    
    
        int mid = l + r >> 1;
        if(a[t[mid]].h >= x) r = mid;
        else l = mid + 1;
    }
    return l;
}

class Solution {
    
    
public:
    int maxEnvelopes(vector<vector<int>>& env) {
    
    
        int n = 0;
        for(auto &u : env) a[++n] = {
    
    u[0], u[1]};
        if(n == 0) return 0;
        
        sort(a + 1, a + n + 1);
        
        tg = 0;
        t[++tg] = 1;
        for(int i = 2; i <= n; ++i) {
    
    
            if(a[i].h > a[t[tg]].h) t[++tg] = i;
            else if(a[i].h < a[t[tg]].h) t[b_s(1, tg, a[i].h)] = i;
        }
        
        return tg;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43900869/article/details/114345000