Cod sursa(job #2706076)

Utilizator Cristian25Cristian Stanciu Cristian25 Data 13 februarie 2021 18:50:35
Problema Subsir crescator maximal Scor 70
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <stdio.h>
#include <stdlib.h>

void type_rec_sol(unsigned* arr, unsigned* scmax, int pos, unsigned cont, FILE* pf)
{
    if(!cont || pos < 0)
        return;
    if(scmax[pos] == cont)
    {
        type_rec_sol(arr, scmax, pos - 1, cont - 1, pf);
        fprintf(pf, "%u ", arr[pos]);
    }
    else type_rec_sol(arr, scmax, pos - 1, cont, pf);
}

void scmax(unsigned* arr, unsigned n)
{
    unsigned* scmax = (unsigned*)calloc(n, sizeof(unsigned));
    if(scmax == NULL)
    {
        perror("Nu s-a putut aloca memorie in mod dinamic pe heap!");
        exit(3); /// return 3;
    }
    unsigned lmax = 1;
    #define MAX(a, b) (((a) > (b)) ? (a) : (b))
    for(unsigned i = 0; i < n; ++i)
    {
        scmax[i] = 1;
        for(unsigned j = 0; j < i; ++j)
            if(arr[j] < arr[i])
            {
                scmax[i] = MAX(scmax[i], scmax[j] + 1);
                lmax = MAX(lmax, scmax[i]);
            }
    }
    #undef MAX
    #define filename "scmax.out"
    #define mode "w"
    FILE* fout = fopen(filename, mode);
    #undef filename
    #undef mode
    fprintf(fout, "%u\n", lmax);
    type_rec_sol(arr, scmax, n - 1, lmax, fout);
    fclose(fout);
}

int main(void)
{
    const char* filename = "scmax.in", *mode = "r";
    FILE* fin = fopen(filename, mode);
    if(fin == NULL)
    {
        perror("Nu s-a putut deschide fisierul text de intrare!");
        exit(1); /// return 1;
    }
    unsigned n;
    fscanf(fin, "%u", &n);
    if(!n)
    {
        fclose(fin);
        return 0;
    }
    unsigned* arr = (unsigned*)malloc(n << 2);
    if(arr == NULL)
    {
        perror("Nu s-a putut aloca memorie pe heap in mod dinamic!");
        exit(2); /// return 2;
    }
    for(unsigned i = 0; i < n; fscanf(fin, "%u", arr + i++));
    fclose(fin);
    scmax(arr, n);
    return 0;
}