Cod sursa(job #3355882)

Utilizator stef_05Stefanescu Andrei-Cosmin stef_05 Data 27 mai 2026 11:54:31
Problema Problema Damelor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <iostream>
#include <tuple>
#include <vector>

using namespace std;

ifstream in("damesah.in");
ofstream out("damesah.out");

vector<int> sol;
bool seen[14];
vector<int> lines(14);
vector<bool> cols(14);
vector<bool> diag1(28);
vector<bool> diag2(28);
int ans;
int n;

bool is_valid(int row, int col) {
    return !cols[col] && !diag1[col - row + n - 1] && !diag2[row + col];
}

void bkt(int row) {
    if (row == n) { // Conditia de oprire / succes
        if (ans < 1) {
            for (auto s : sol) {
                out << s << ' ';
            }
            out << '\n';
        }
        ans++;
    }

    for (int col = 1; col <= n; col++) { // Toate candidaturile posibile
        if (is_valid(row, col)) {        // Validare
            // 1. Fa pasul
            cols[col] = diag1[col - row + n - 1] = diag2[row + col] = true;
            sol.push_back(col);

            // 2. Intra in recursivitate
            bkt(row + 1);

            // 3. ANULEAZA pasul (Undo pt urmatoarea ramura)
            cols[col] = diag1[col - row + n - 1] = diag2[row + col] = false;
            sol.pop_back();
        }
    }
}

int main() {
    in >> n;

    ans = 0;
    bkt(0);
    out << ans << '\n';
}