Cod sursa(job #1693502)

Utilizator sdwolfSDWOLF sdwolf Data 23 aprilie 2016 11:42:26
Problema Generare de permutari Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.43 kb
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int main() {
  FILE *input, *output;
  int size, index, position, current;
  int *stack;
  bool added, valid, in_stack;
  bool *appearance;

  input  = fopen("permutari.in", "r");
  fscanf(input, "%d\n", &size);
  fclose(input);

  stack      = (int*) malloc(sizeof(int) * (size));
  appearance = (bool*) malloc(sizeof(int) * (size + 1));

  for(index = 0; index < size; index += 1) {
    stack[index]      = 0;
    appearance[index] = false;
  }

  output = fopen("permutari.out", "w");

  position = 0;
  while (position > -1) {
    if (position < size) {
      added = false;
      current = stack[position];

      for(index = current + 1; index <= size; index += 1) {
        in_stack = appearance[index];

        if (!in_stack) {
          current             = stack[position];
          appearance[current] = false;
          stack[position]     = index;
          appearance[index]   = true;
          added               = true;
          position            += 1;

          break;
        }
      }

      if (!added) {
        current             = stack[position];
        appearance[current] = false;
        stack[position]     = 0;
        position            -= 1;
      }
    } else {
      position -= 1;

      for(index = 0; index < size; index += 1) {
        fprintf(output, "%d ", stack[index]);
      }
      fprintf(output, "\n");
    }
  }

  fclose(output);

  return 0;
}