Cod sursa(job #2416890)

Utilizator avtobusAvtobus avtobus Data 28 aprilie 2019 15:00:49
Problema Generare de permutari Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
// Permutari: cu backtracking

#include <stdio.h>
#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < n; i++)
#define REP(i,a,b) for(int i = a; i < b; i++)

using namespace std;
typedef pair<int, int> pii;
const int INF = 0x3f3f3f3f;

int N, d[10];

void go(int);
void write();

int main(void) {
  freopen("permutari.in", "r", stdin);
  freopen("permutari.out", "w", stdout);
  cin >> N;
  rep(i, N) { d[i] = i+1; }
  go(0);
  return 0;
}

void write() {
  rep(i, N) { cout << d[i] << ' '; }
  cout << '\n';
}

void go(int lvl) {
  if (lvl == N) {
    write();
    return;
  }

  for (int i = lvl; i < N; i++) {
    swap(d[lvl], d[i]);
    go(lvl+1);
  }
  // return d[lvl..N] to the initial position
  for (int i = lvl; i < N-1; i++) {
    swap(d[i], d[i+1]);
  }
}