Cod sursa(job #2610961)

Utilizator andreihaivas006Daniel Haivas andreihaivas006 Data 5 mai 2020 22:33:01
Problema Subsir crescator maximal Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
/*
    dp[i] = lungimea subsirului maximal crescator pana la poz i (inclusiv)
            //////dp[i] = lungimea subsirului maximal crescator care incepe pe poz i (luam de la coada)

    dp[i] = 1 + max(dp[j])   , j = 1 .. i
              s[i] > s[j]
    solutie: max(dp[])
*/
#include <iostream>
#include <stdio.h>
#include <fstream>

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

int n, s[100000];
int dp[100000], pred[100000];

int scmax(int i)
{
    if (dp[i] != 0)
        return dp[i];
    int max = 0;
    for (int j = 1; j < i; j++)
        if (scmax(j) > max && s[i] > s[j])
            max = scmax(j);
    return dp[i] = 1 + max;
}

void afisare_rec(int indice)
{
    if (indice == -1)
        return;
    afisare_rec(pred[indice]);
    fout << s[indice] << " ";
}

void scmax_()
{
    dp[1] = 1;
    for (int i = 2; i <= n; i++)//(int i = n; i >= 1; i--)
    {
        int max = 0;
        int indice = -1;
        for (int j = 1; j < i; j++)//(int j = i + 1; j <= n; j++)
            if (s[i] > s[j] && dp[j] > max)
            {
                max = dp[j];
                indice = j;
            }
        dp[i] = 1 + max;
        pred[i] = indice;
    }
    int max = dp[1];
    int indice = 1;
    for (int i = 1; i <= n; i++)
        if (dp[i] > max)
        {
            max = dp[i];
            indice = i;
        }
    fout << max << "\n";
    // afiseaza in ordine inversa
    // folosim o functie recursiva ce afiseaza cand goleste stiva
    /*while (indice != -1)
    {
        cout << s[indice] << " ";
        indice = pred[indice];
    }*/
    afisare_rec(indice);
}

int main()
{
    fin >> n;
    for (int i = 1; i <= n; i++)
        fin >> s[i];
    scmax_();
    return 0;
}