Cod sursa(job #3369297)

Utilizator rapidu36Victor Manz rapidu36 Data 19 octombrie 2026 15:35:57
Problema Subsir crescator maximal Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.06 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <climits>

using namespace std;

void normalizare(vector <int> &v_ini, vector <int> &v) {
    int n = (int) v_ini.size();
    vector <pair <int, int>> aux(n);
    for (int i = 0; i < n; i++) {
        aux[i].first = v_ini[i];
        aux[i].second = i;
    }
    sort(aux.begin(), aux.end());
    int val_c = 0;
    v[aux[0].second] = ++val_c;
    for (int i = 1; i < n; i++) {
        if (aux[i - 1].first < aux[i].first) {
            ++val_c;
        }
        v[aux[i].second] = val_c;
    }
}

int interogare(vector <int> &aib, int poz) {
    int maxim = 0;
    while (poz != 0) {
        maxim = max(maxim, aib[poz]);
        int p2 = (poz & -poz);
        poz -= p2;
    }
    return maxim;
}

void actualizare(vector <int> &aib, int n, int poz, int val) {
    while (poz <= n) {
        aib[poz] = max(aib[poz], val);
        int p2 = (poz & -poz);
        poz += p2;
    }
}

void refac_subsirul(vector <int> &v_ini, vector <int> &lung,
    int poz, int lung_c, int reper, ofstream &fout) {
    if (lung_c == 0) {
        return;
    }
    if (lung[poz] == lung_c && v_ini[poz] < reper) {
        refac_subsirul(v_ini, lung,
            poz - 1, lung_c - 1, v_ini[poz], fout);
        fout << v_ini[poz] << " ";
    } else {
        refac_subsirul(v_ini, lung, poz - 1, lung_c, reper, fout);
    }
}

int main() {
    ifstream fin("scmax.in");
    ofstream fout("scmax.out");
    int n;
    fin >> n;
    vector <int> v_ini(n);
    for (int i = 0; i < n; i++) {
        fin >> v_ini[i];
    }
    fin.close();
    vector <int> v(n);
    normalizare(v_ini, v);
    vector <int> aib(n + 1, 0);
    vector <int> lung(n, 0);
    int poz_max = 0;
    for (int i = 0; i < n; i++) {
        int l = interogare(aib, v[i] - 1);
        lung[i] = l + 1;
        if (lung[i] > lung[poz_max]) {
            poz_max = i;
        }
        actualizare(aib, n, v[i], lung[i]);
    }
    fout << lung[poz_max] << "\n";
    refac_subsirul(v_ini, lung,
        poz_max, lung[poz_max], INT_MAX, fout);
    fout << "\n";
    fout.close();
    return 0;
}