Cod sursa(job #2437073)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 8 iulie 2019 12:54:46
Problema Problema Damelor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>

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

int n;
int perm[20];

int cnt;
int sol[20];
bool used[20];

inline int abs(int x) {
    return x < 0 ? -x : x;
}

bool check(int pos, int val) {
    for (int i = 1; i < pos; i++)
        if (pos - i == abs(val - perm[i]))
            return false;
    return true;
}

void bkt(int pos) {
    if (pos == n + 1) {
        if (!cnt)
            for (int i = 1; i <= n; i++)
                sol[i] = perm[i];
        cnt++;
        return;
    }

    for (int i = 1; i <= n; i++)
        if (!used[i] && check(pos, i)) {
            used[perm[pos] = i] = true;
            bkt(pos + 1);
            used[i] = false;
        }
}

int main() {
    fin >> n;
    bkt(1);

    for (int i = 1; i <= n; i++)
        fout << sol[i] << ' ';
    fout << '\n' << cnt << '\n';

    fout.close();
    return 0;
}