Cod sursa(job #2610962)

Utilizator andreihaivas006Daniel Haivas andreihaivas006 Data 5 mai 2020 22:36:05
Problema Subsir crescator maximal Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 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 pt reconstituirea solutiei)

    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[n] = 1;
    for (int i = n; i >= 1; i--)//(int i = n; i >= 1; i--)
    {
        int max = 0;
        int indice = -1;
        for (int j = i + 1; j <= n; 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";

    while (indice != -1)
    {
        fout << s[indice] << " ";
        indice = pred[indice];
    }
}

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