Cod sursa(job #3250321)

Utilizator RaresHRares Hanganu RaresH Data 20 octombrie 2024 11:04:33
Problema Generare de permutari Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <stdio.h>

const int MAXN = 10;
const int NIL = 0;

FILE *fin, *fout;
int n;
char next[MAXN + 1], perm[MAXN];

void gen_perms(int pos) {
  if(pos >= n) {
    for(int i = 0; i < n; i++) {
      fprintf(fout, "%d ", perm[i]);
    }
    fprintf(fout, "\n");
  } else {
    int i = 0;
    while(next[i] != NIL) {
      perm[pos] = next[i];
      int cop = next[i];
      next[i] = next[(int)next[i]];
      gen_perms(pos + 1);
      next[i] = cop;
      i = next[i];
    }
  }
}

int main() {
  int i;

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

  for(i = 1; i < n; i++) {
    next[i] = i + 1;
  }
  next[0] = 1;
  next[n] = NIL;

  fout = fopen("permutari.out", "w");
  gen_perms(0);
  fclose(fout);

  return 0;
}