Cod sursa(job #2923549)

Utilizator VladPislaruPislaru Vlad Rares VladPislaru Data 15 septembrie 2022 18:07:31
Problema Subsir crescator maximal Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MaxN = 100005;

int n, a[MaxN], dp_val[MaxN], dp_pos[MaxN], aib_val[MaxN], aib_pos[MaxN], bst, up[MaxN];
vector <int> ind (MaxN);


void Update(int k, int val, int i)
{
    while (k <= n)
    {
        if (aib_val[k] < val) {
            aib_val[k] = val;
            aib_pos[k] = i;
        }
        k = k + (k & -k);
    }
}


pair <int, int> Query(int k)
{
	int val_max = 0, pos = -1;
	while (k > 0) {
        if (aib_val[k] > val_max) {
            val_max = aib_val[k];
            pos = aib_pos[k];
        }
        k = k - (k & -k);
	}
	return {val_max, pos};
}

int main()
{
	int i;
	fin >> n;
	ind.resize(n);
	for (i = 1; i <= n; i++){
		fin >> a[i];
		ind[i - 1] = a[i];
	}
	sort(ind.begin(), ind.end());
	ind.erase(unique(ind.begin(), ind.end()), ind.end());
	for (i = 1; i <= n; ++i)
		a[i] = lower_bound(ind.begin(), ind.end(), a[i]) - ind.begin() + 1;
	for (i = 1; i <= n; i++)
	{
	    pair <int, int> elem = Query(a[i]);
		dp_val[i] = elem.first + 1;
		dp_pos[i] = elem.second;
		Update(a[i] + 1, dp_val[i], i);
	}
	int best_val = 0, best_pos = 0;
	for (i = 1; i <= n; i++)
		if (best_val < dp_val[i]) {
            best_val = dp_val[i];
            best_pos = i;
		}
	fout << best_val << "\n";
	vector <int> ans;
	while (best_pos != -1) {
        ans.push_back(ind[a[best_pos]]);
        best_pos = dp_pos[best_pos];
	}
	for (auto i = ans.rbegin(); i != ans.rend(); i++)
        fout << *i << " ";
    fout << "\n";
	return 0;
}