Cod sursa(job #3129073)

Utilizator ADelegeanuAlex Delegeanu ADelegeanu Data 12 mai 2023 15:09:06
Problema Subsir crescator maximal Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <bits/stdc++.h>

void printVect(const std::vector<int>& v) {
    for (auto x : v) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
}

std::vector<int> bestSeq(const std::vector<int>& nums) {
    std::vector<int> best{};
    best.reserve(nums.size());

    best.push_back(1);
    int bestLength = 1;
    for (auto i = 1u; i < nums.size(); i++) {
        int bst = 0;
        for (int j = i - 1; j >= 0; --j) {
            if (nums[i] > nums[j] && best[j] > bst) {
                bst = best[j];
            }
        }
        best.push_back(bst + 1);

        if (best[i] > bestLength)
            bestLength = best[i];
    }

    // printVect(best);

    int bestPos = nums.size() - 1;
    while (bestPos > 0) {
        if (best[bestPos] == bestLength)
            break;
        bestPos--;
    }

    std::vector<int> res;
    res.reserve(bestLength);
    for (int i = bestPos; i > 0; --i) {
        if (best[i] == bestLength) {
            res.push_back(nums[i]);
            bestLength--;
        }
    }

    return std::vector<int>(res.rbegin(), res.rend());
}

int main() {
    std::ifstream iStream("scmax.in");
    int size{ 0 };
    iStream >> size;
    std::vector<int> nums(size);
    for (int i = 0; i < size; i++)
        iStream >> nums[i];
    iStream.close();

    std::ofstream oStream("scmax.out");
    auto res = bestSeq(nums);
    oStream << res.size() << '\n';
    for (auto val : res)
        oStream << val << ' ';
    oStream.close();

    return 0;
}