Cod sursa(job #3307397)

Utilizator stefangr2008Grecu Stefan stefangr2008 Data 20 august 2025 16:09:31
Problema Problema Damelor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.79 kb
#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;

int n, x[101], ok = 0,
    nrsol;

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


bool valid(int k)
{
    for(int i = 1; i < k; i++)
        if(x[k] == x[i] || k - i == abs(x[k] - x[i]))
            return 0;
    return 1;
}

void afis()
{
    for(int i = 1; i <= n; i++)
        g << x[i] << ' ';
}

void backt(int k)
{
    if(k <= n)
    {
        for(int v = 1; v <= n; v++)
        {
            x[k] = v;
            if(valid(k))
                backt(k + 1);
        }
    }
    else{nrsol++;
    if(ok == 0){
            afis();ok++;}}

}

int main()
{
    f >> n;
    backt(1);
    g << '\n' << nrsol << '\n';
    f.close();
    g.close();
    return 0;
}