Cod sursa(job #2746411)

Utilizator Ionut2791Voicila Ionut Marius Ionut2791 Data 27 aprilie 2021 20:00:42
Problema Subsir crescator maximal Scor 45
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.54 kb
#include <bits/stdc++.h>
#define ll long long
#define sz(x) (int)(x).size()
#define LSB(a) ((-a) & a)
using namespace std;

#ifdef LOCAL
#define read() ifstream fin("date.in.txt");
#else
#define read() ifstream fin("scmax.in"); ofstream fout("scmax.out");
#endif // LOCAL

const int N = 100005;
int n, AIB[N];
int v[N];
int actPosInVector[N];
map<int,int> idx;
set<int> vals;
int from[N];

int searchMax(int pos, int val) {
    int pMax = 0;
    while(pos > 0) {

        if(AIB[pMax] < AIB[pos] && v[actPosInVector[pos]] < val)
            pMax = pos;

        pos -= LSB(pos);
    }
    return pMax;
}

void update(int pos, int val, int actAdded,  int idxFrom) {
    while(pos <= n) {

        if(AIB[pos] < val) {
            AIB[pos] = val;
            actPosInVector[pos] = actAdded;
            from[pos] = idxFrom;
        }
        else if(AIB[pos] == val && v[actPosInVector[pos]] > v[actAdded]) {
            actPosInVector[pos] = actAdded;
            from[pos] = idxFrom;
        }

        pos += LSB(pos);
    }
}


int main() {
    read();
    fin >> n;

    for (int i = 1; i <= n; ++i) {
        fin >> v[i];
        vals.insert(v[i]);
    }
    int p = 1;
    for (int x : vals) {
        idx[x] = p++;
    }

    for (int i = 1; i <= n; ++i) {
        int posSecvMax = searchMax(idx[v[i]], v[i]);

        //cout << posSecvMax << " " << v[i]  << " " << actPosInVector[posSecvMax]<< '\n';

        update(idx[v[i]], AIB[posSecvMax] + 1, i, idx[v[actPosInVector[posSecvMax]]]);

        /*for (int j = 1; j <= n; ++j) {
            cout << AIB[j] << " ";
        }
        cout << '\n';
        for (int j = 1; j <= n; ++j) {
            cout << v[actPosInVector[j]] << " ";
        }
        cout << '\n';
        for (int j = 1; j <= n; ++j) {
            cout << from[j] << " ";
        }
        cout << '\n';
        cout << '\n';
        */
    }

    int best = searchMax(n, INT_MAX);
    #ifdef LOCAL
    cout << AIB[best] << '\n';

    vector<int> drum;
    int x = best;
    while(x != 0) {
        drum.push_back(v[actPosInVector[x]]);
        x = from[x];
    }

    reverse(drum.begin(), drum.end());
    for (int x : drum)
        cout << x << " ";
    #else
    fout << AIB[best] << '\n';

    vector<int> drum;
    int x = best;
    while(x != 0) {
        drum.push_back(v[actPosInVector[x]]);
        x = from[x];
    }

    reverse(drum.begin(), drum.end());
    for (int x : drum)
        fout << x << " ";
    #endif // LOCAL

    return 0;
}