Cod sursa(job #2720691)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 11 martie 2021 10:26:58
Problema Subsir crescator maximal Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stack>

using namespace std;

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

const int NMax = 1e5;

struct ValuePosition{
    int value, position;
    bool operator < (const ValuePosition other) const{
        if (value == other.value)
            return position > other.position;
        return value < other.value;
    }
}v[NMax + 5];

stack <int> st;
int n, posmax;
int initial[NMax + 5], dp[NMax + 5], aib[NMax + 5], previous[NMax + 5];

void Read(){
    fin >> n;
    for (int i = 1; i <= n; i++){
        fin >> initial[i];
        v[i].value = initial[i];
        v[i].position = i;
    }
}

int Query(int pos){
    int ans = 0;
    for (int i = pos; i >= 1; i -= i & (-i))
        if (dp[aib[i]] > dp[ans])
            ans = aib[i];
    return ans;
}

void Update(int pos){
    for (int i = pos; i <= n; i += i & (-i))
        if (dp[aib[i]] < dp[pos])
            aib[i] = pos;
}

void Solve(){
    sort(v + 1, v + n + 1);
    for (int i = 1; i <= n; i++){
        int position = Query(v[i].position - 1);
        dp[v[i].position] = dp[position] + 1;
        previous[v[i].position] = position;
        if (dp[v[i].position] > dp[posmax])
            posmax = v[i].position;
        Update(v[i].position);
    }
}

void Print(){
    fout << dp[posmax] << '\n';
    int pos = posmax;
    while (pos){
        st.push(pos);
        pos = previous[pos];
    }
    while (!st.empty()){
        fout << initial[st.top()] << ' ';
        st.pop();
    }
    fout << '\n';
}

int main(){
    Read();
    Solve();
    Print();
    return 0;
}