Cod sursa(job #1199213)

Utilizator vlad.doruIon Vlad-Doru vlad.doru Data 18 iunie 2014 16:20:10
Problema Subsir crescator maximal Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.33 kb
#include <stdio.h>
#include <stdlib.h>

int min(int x, int y){
  return x < y ? x : y;
}

int main(int argc, char** argv){
  int n;

  FILE* in = fopen("scmax.in", "r");
  FILE* out = fopen("scmax.out", "w");

  fscanf(in, "%d", &n);

  int i;
  int *v = (int*)malloc(n * sizeof(int));
  int *dp = (int*)calloc(n, sizeof(int));
  int *index = (int*)malloc(n * sizeof(int));
  int *prec = (int*)calloc(n, sizeof(int));
  // dp[i] Valoarea minima a subsirului crescator maximal de lungime i

  int size = 0;
  int position, step;
  index[0] = -1;

  for(i = 0; i < n; ++i){
    fscanf(in, "%d", &v[i]);

    // printf("size %d\n", size);
    // Efectuam cautare binara
    for (step = 1; step < size; step<<=1);
    for (position=0; step; step>>=1) {
      if (position + step <= size && dp[position + step] < v[i]) {
        position += step;
      }
    }

    // Actualizam vector dp
    if (position == size) {
      size++;
    }
    dp[position+1] = v[i];
    index[position + 1] = i;
    prec[i] = index[position];
  }

  fprintf(out, "%d\n", size);

  // Refolosim vectorul index pt afisarea solutiilor
  int aux = size;
  for (position = index[size]; position != -1; position = prec[position]) {
    index[--aux] = v[position];
  }
  for (i=0; i<size; ++i){
    fprintf(out, "%d ", index[i]);
  }

  free(v);
  free(dp);
  free(index);


  return 0;
}