Cod sursa(job #2240382)

Utilizator valkir69Radu Andrei valkir69 Data 13 septembrie 2018 10:29:24
Problema Problema Damelor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;

typedef int stacks[100];

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

int n,m,k,nrsol;

stacks st;

bool as,ev, printed = false;

void init(){
    st[k] = 0;
}

bool successor(){
    if(st[k] < n){st[k]++; return true;}
    else return false;
}

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

bool sol(){
    return k == n;
}

/*void print()
{
    for(int i=1;i<=k;i++){
        for(int j=1;j<=k;j++)
            if(st[j]==j)
               cout<<"D ";
            else
                cout<<"*";
        cout<<"\n";
    }
    cout<<"\n";
}*/

void print(){
    for(int i = 1; i <= n; ++i) g << st[i] << " ";
    g << "\n";
}

void backtrack(){
    k = 1;
    init();
    while(k > 0){
        as = true; ev = false;
        while(as && !ev){
            as = successor();
            if(as) ev = valid();
        }
        if(as){
            if(sol()){
                nrsol++;
                while(!printed){print(); printed = true;}
             }
            else {k++; init();}
        }
        else k--;
    }
}

int main()
{
    f >> n;
    backtrack();
    g << nrsol;
    f.close();
    g.close();
    return 0;
}