Cod sursa(job #3222714)

Utilizator Alex_DumitrascuAlex Dumitrascu Alex_Dumitrascu Data 11 aprilie 2024 14:37:32
Problema Subsir crescator maximal Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ("scmax.in");
ofstream fout ("scmax.out");

int dp[100005];
int v [100005];
int pre[100005];
int index[100005];
int n;
void debug (int arr[])
{
    for (int i=1; i<=n; i++) {
        cout<<arr[i]<<' ';
    }
    cout<<endl;
}
/*
Subproblema: cel mai lung subsir
crescator maximal care incepe cu pozitia i.
*/
int main()
{
    cin.tie(0); cin.sync_with_stdio(false);
    cout.tie(0); cout.sync_with_stdio(false);
    int elem;
    fin>>n;
    for (int i=1; i<=n; i++) {
        fin>>v[i];
        dp[i]=INT_MAX;
    }
    dp[0]=0;
    for (int i=1; i<=n; i++) {
        //for (int l=1; l<=n; l++) {
            ///This if is the equivalent of upper_bound
            ///https://cp-algorithms.com/sequences/longest_increasing_subsequence.html
            /*
            if (dp[l-1]<v[i]&&v[i]<dp[l]) {
                dp[l]=v[i];
            }
            */
        //}
        //TODO: Restore the subsequence
        int l=upper_bound(dp+1, dp+n+1, v[i])-dp;
        if (dp[l-1]<v[i]&&v[i]<dp[l]) {
            dp[l]=v[i];
            index[l]=i;
            pre[i]=index[l-1];
        }
    }
    int bst=0;
    for (int i=1; i<=n; i++) {
        if (dp[i]<INT_MAX)
            bst=i;
    }
    fout<<bst<<'\n';
    //debug(dp);
    //debug(pre);
    stack <int> st;
    bst=index[bst];
    while (pre[bst]!=0) {
        st.push(v[bst]);
        bst=pre[bst];
    }
    st.push(v[bst]);
    while (!st.empty()) {
        fout<<st.top()<<' ';
        st.pop();
    }
    return 0;
}