Cod sursa(job #1693485)

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

int main() {
  FILE *input, *output;
  int size, index, position, element;
  int *stack;
  bool 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;
  }

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

  position = 0;
  while (position > -1) {
    if (stack[position] < size) {
      stack[position] += 1;
      position        += 1;
    } else {
      stack[position] = 0;
      position -= 1;
    }

    if (position == size) {
      position -= 1;

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

      valid = true;

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

        if (in_stack) {
          valid = false;
          break;
        }

        appearance[element] = true;
      }

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

  fclose(output);

  return 0;
}