Cod sursa(job #3150428)

Utilizator MilitaruMihai2022Millitaru Mihai MilitaruMihai2022 Data 16 septembrie 2023 16:39:32
Problema Problema Damelor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int n,x[15],nrsol=0;
bool ok=0;

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

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 backt()
{
    int k = 1;
    x[1] = 0;
    while(k > 0)
        if(x[k] < n)
        {
            x[k]++;
            if(valid(k))
            {
                if(k == n)
                {
                    afis();
                    ok=1;
                }
                else
                    x[++k] = 0;
            }
        }
        else
            k--;
}

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