Cod sursa(job #3261921)

Utilizator KRISTY06Mateiu Ianis Cristian Vasile KRISTY06 Data 7 decembrie 2024 19:41:25
Problema Subsir crescator maximal Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
#include <bits/stdc++.h>
using namespace std;

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

pair<int, int> tree[400001];

set<int> sortedNums;

map<int, set<int>> numPos;

int neighbours[100001], a[100001], sortedNumsLen;

pair<int, int> findMaxLen(int left, int right, int currentNode, int pos) {
    if (left > pos) {
        return {0, 0};
    } else if (right <= pos) {
        return tree[currentNode];
    }
    return max(findMaxLen(left, (left + right) / 2, currentNode * 2, pos), findMaxLen((left + right) / 2 + 1, right, currentNode * 2 + 1, pos));
}

void update(int left, int right, int currentNode, int newLen, int pos) {
    if (right < pos || left > pos) {
        return;
    } else if (left == right) {
        tree[currentNode] = {newLen, pos};
        return;
    }
    update(left, (left + right) / 2, currentNode * 2, newLen, pos);
    update((left + right) / 2 + 1, right, currentNode * 2 + 1, newLen, pos);
    tree[currentNode] = max(tree[currentNode * 2], tree[currentNode * 2 + 1]);
}

void output(int pos) {
    if (neighbours[pos] == 0) {
        fout << a[pos] << ' ';
        return;
    }
    output(neighbours[pos]);
    fout << a[pos] << ' ';
}

int main() {
    ios_base::sync_with_stdio(false);
    fin.tie(NULL);
    int n;
    fin >> n;
    for (int i = 1; i <= n; ++i) {
        fin >> a[i];
        sortedNums.insert(a[i]);
        numPos[a[i]].insert(i);
    }
    int ansLen = 0, lastPos = 0;
    for (set<int>::iterator it = sortedNums.begin(); it != sortedNums.end(); ++it) {
        pair<int, int> maxSubSeq = {0, 0};
        int maxSubSeqLastPos = *numPos[*it].begin();
        for (set<int>::iterator pos = numPos[*it].begin(); pos != numPos[*it].end(); ++pos) {
            pair<int, int> subSeq = findMaxLen(1, n, 1, *pos - 1);
            if (subSeq > maxSubSeq) {
                maxSubSeq = subSeq;
                maxSubSeqLastPos = *pos;
            }
        }
        update(1, n, 1, maxSubSeq.first + 1, maxSubSeqLastPos);
        neighbours[maxSubSeqLastPos] = maxSubSeq.second;
        if (maxSubSeq.first + 1 > ansLen) {
            ansLen = maxSubSeq.first + 1;
            lastPos = maxSubSeqLastPos;
        }
    }
    fout << ansLen << '\n';
    output(lastPos);
    return 0;
}