Cod sursa(job #2241608)

Utilizator Dragos123Tatar Dragos Vlad Dragos123 Data 16 septembrie 2018 14:28:29
Problema Generare de permutari Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include <fstream>
#include <iostream>

std::ifstream fin ("permutari.in");
std::ofstream fout ("permutari.out");

const int MaxN = 9;
int n, a[MaxN];

void Write();
bool Ok(int pos);
void Back_Track(int pos);

int main ()
{
    fin >> n;
    Back_Track(1);
    return 0;
}

void Write()
{
    for (int i = 1; i <= n; ++i)
        fout << a[i] << ' ';
    fout << '\n';
}

bool Ok(int pos)
{
    for (int i = 1; i <= pos - 1; ++i)
        if (a[pos] == a[i])
            return false;
    return true;
}

void Back_Track(int pos)
{
    for (int i = 1; i <= n; ++i)
    {
        a[pos] = i;
        if (Ok(pos))
        {
            if (pos == n)
                Write();
            else
                Back_Track(pos + 1);
        }
    }
}