Cod sursa(job #3321932)

Utilizator andrei_toaderToader Andrei Sorin andrei_toader Data 11 noiembrie 2025 19:37:08
Problema Generare de permutari Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>

using namespace std;
int n;
int permutations[10];

fstream f("permutari.in");
ofstream g("permutari.out");

bool is_solution(int k) {
    return k == n;
}

void write_to_file() {
    for (int i = 1; i<=n; i++) {
        g<< permutations[i]<< " ";
    }

    g<<"\n";
}

bool is_possible_solution(int k) {
    for (int i = 1; i < k; i++) {
        if (permutations[i] == permutations[k]) {
            return false;
        }
    }

    return true;
}

void backtracking() {
    int k = 1;
    permutations[1] = 0;
    while (k > 0) {
        if (permutations[k] < n) {
            permutations[k]++;
            if (is_possible_solution(k))
            {
                if (is_solution(k)) {
                    write_to_file();
                }
                else 
                {
                    k++;
                    permutations[k] = 0;
                }
            }
        }
        else {
            k--;
        }
    }
}

int main() {
    f >>n;
    backtracking();
    return 0;
}