#include <stdio.h>
#include <algorithm>
#include <stack>
#include <vector>
using namespace std;
int n, arr[300010], INDEX[300010];
vector<int> v;
stack<int> st;

int main() {
    scanf("%d", &n);
    for(int i=0; i<n; i++) {
        scanf("%d", &arr[i]);
    }
    for(int i=0; i<n; i++) {
        int lo=upper_bound(v.begin(), v.end(), arr[i])-v.begin();
        if(lo==v.size()) v.push_back(arr[i]);
        else v[lo]=arr[i];

        INDEX[i]=lo;
    }

    int idx=v.size()-1, pre=1; //LIS 역추적

    // 역추적
    for(int i=n-1; i>=0; i--) {
        if(INDEX[i]==idx) {
            st.push(i);
            idx--;
        }
    }

    printf("%d\n", n-(int)v.size());
    for(int i=0; i<n; i++) {
        if(!st.empty()&&st.top()==i) {
            printf("%d ", arr[i]);
            st.pop(); pre=arr[i];
        }
        else printf("%d ", pre);
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: