求最长且字典项最小的递增子序列

增加ends数组,记录以每一个a[i]为结尾的最长递增子序列长度,然后从后遍历判断输出

#include
using namespace std;
int a[100001], endS[100001];
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    int n; cin >> n;
    for(int i = 0; i < n; i++)cin>>a[i];
    vector<int>high;
    for(int i = 0; i < n; i++){
        auto it = lower_bound(high.begin(), high.end(), a[i]);
        if(it == high.end())high.push_back(a[i]), endS[i] = high.size();
        else *it = a[i], endS[i] = it - high.begin() + 1;
    }
    vector<int>ans;
    int lenAns = high.size();
    for(int i = n - 1; i >= 0; i--){
        if(endS[i] == lenAns)ans.push_back(a[i]), lenAns--;
    }
    reverse(ans.begin(), ans.end());
    for(auto i : ans)cout << i << ' ';
}

你可能感兴趣的:(算法,c++,数据结构)