Cod sursa(job #3325264)

Utilizator zionlyismAdobroaiei David zionlyism Data 25 noiembrie 2025 09:29:21
Problema Subsir crescator maximal Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>

#define NMAX 100002
using namespace std;

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

int a[NMAX], n; //vector a cu n elemente

int best[NMAX], poz[NMAX];
int lgbest;
//best[i] = cel mai mic element care poate fi plasat pe poz i intr-un LIS
//poz[i] = pozitia pe care a fost plasat a[i] in best

int stiva[NMAX];
int vf;

int cautbin(int x);

int main()
{
    int i, rez;
    fin>>n;
    for(i = 1; i <= n; i++) fin>>a[i];
    //initializare
    best[1] = a[1]; poz[1] = 1; lgbest = 1; //primul element din a
    for(i = 2; i <= n; i++)
        //pot adauga pe a[i] la sfarsitul lui best
        if(a[i] > best[lgbest])
        {
           best[++lgbest] = a[i]; poz[i] = lgbest;
        }
        else
        {
           rez = cautbin(a[i]); //pozitia pe care il pot pune pe a[i] intr-un LIS
           best[rez] = a[i];
           poz[i] = rez;
        }
    fout<<lgbest<<'\n';
    //reconstituim subsirul
    rez = lgbest; //pozitia care imi trebuie (gasesc primul 7, primul 6, primul 5..., primul 1 in vectorul poz)
    for(i = n; i > 0; i--)
        if(poz[i] == rez)
        {
           stiva[++vf] = a[i];
           rez--;
        }
    while(vf) fout<<stiva[vf--]<<' ';
    return 0;
}

int cautbin(int x)
{
 int st = 0, dr = lgbest + 1, mij;
 while(dr - st > 1)
 {
     mij = (st + dr) / 2;
     //invariantul: best[st] <= x < best[dr]
     if(best[mij] <= x)
        st = mij;
        else
        dr = mij;
 }
 return dr;
}