Cod sursa(job #2610946)

Utilizator andreihaivas006Daniel Haivas andreihaivas006 Data 5 mai 2020 22:06:00
Problema Subsir crescator maximal Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
/*
    dp[i] = lungimea subsirului maximal crescator care incepe pe poz i(INCLUSIV ELEMENTUL i)

    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];
    if (i == 1)
        return dp[1] = 0;

    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 scmax_()
{
    for (int i = n; i >= 1; i--)
    {
        int max = 0;
        int indice = -1;
        for (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;
}