Leetcode354. Two-dimensional nesting problem (converted to one-dimensional LIS)

Meaning:
given nnThe leader of group n isai a_iai, The width is bi b_ibiThe red envelope, if ai <aj a_i<a_jai<aj b i < b j b_i<b_j bi<bj, Then red envelope iii can be installed in red envelopejjj . Now ask you how many red envelopes you can nest at most at a time.
Data range:1 ≤ n ≤ 1 0 5, 1 ≤ ai, bi ≤ 1 0 9 1\leq n\leq 10^5,1\leq a_i,b_i\leq 10^91n105,1ai,bi109

Solution:
Consider the first dimension aa in ascending ordera and thenbbfor the second dimensionb Do LIS again. The problem here is that there may be the sameaaa red envelope nested within each other, which is not in line with the requirements, so we have a second dimensionbbb is sorted in descending order to ensure that each dimensionaaA can only be selected at most one.

Code:

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

Guess you like

Origin blog.csdn.net/weixin_43900869/article/details/114345000