[Hdp] lc1713. The minimum number of operations to get the subsequence (LIS+LCS optimization+weekly contest 222_4)

1. Source of the subject

Link: 1713. Get the minimum number of operations for the subsequence

2. Topic analysis

Foreword:

A very important knowledge point. When the array elements will not be repeated when the LCSproblem can be transformed into LISthe problem. LISGreedy can reduce the time complexity from O (n 2) O(n^2)O ( n2 )GetO (nlogn) O(nlogn)O ( n- L O G n- ) , comprising the processing10^5capability of the data range.

But LISthe greedy wording design to two points, find many of the border. It is recommended to directly back off the board!
Insert picture description here

  • Time complexity : O (nlogn) O(nlogn)O ( n l o g n )
  • Space complexity : O (n) O(n)O ( n )

Code:

class Solution {
    
    
public:
    int minOperations(vector<int>& target, vector<int>& arr) {
    
    
        unordered_map<int, int> hash;
        for (int i = 0; i < target.size(); i ++ ) 
            hash[target[i]] = i;
        
        vector<int> a;
        for (int i = 0; i < arr.size(); i ++ ) 
            if (hash.count(arr[i]))
                a.push_back(hash[arr[i]]);
        
        int len = 0;
        vector<int> q(a.size() + 1);
        for (int i = 0; i < a.size(); i ++ ) {
    
    
            int l = 0, r = len;
            while (l < r) {
    
    
                int mid = l + r + 1 >> 1;
                if (q[mid] < a[i]) l = mid;
                else r = mid - 1;
            }
            len = max(len, r + 1);
            q[r + 1] = a[i];
        }
        return target.size() - len;
    }
};

Guess you like

Origin blog.csdn.net/yl_puyu/article/details/112145022
HDP