Cod sursa(job #1730889)

Utilizator jurjstyleJurj Andrei jurjstyle Data 17 iulie 2016 19:31:30
Problema Problema Damelor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <cmath>

using namespace std ;

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

int n , nr_sol , x[15] ;

void afis ()
{
 ++nr_sol ;
 if ( nr_sol == 1 )
     {
      for ( int j = 1 ; j <= n ; ++j )
            g << x[j] << " " ;
      g << "\n" ;
     }
}

int abs ( int x )
{
 if ( x < 0 )
    return x * ( -1 ) ;
 return x ;
}

int ok ( int i , int j )
{
 x[i] = j ;
 for ( int cnt = 1 ; cnt < i ; ++cnt )
    if ( x[i] == x[cnt] || abs ( x[i] - x[cnt] ) == i - cnt )
        return 0 ;
  return 1 ;
}

void back ( int k )
{
 if ( k == n + 1 )
    afis () ;
 else if ( k <= n )
    {
     for ( int j = 1 ; j <= n ; ++j )
        if ( ok ( k , j ) )
                {
                 x[k] = j ;
                 back ( k + 1 ) ;
                 x[k] = 0 ;
                }
    }
}

int main ()
{
 f >> n ;
 back ( 1 ) ;
 g << nr_sol ;
}