Cod sursa(job #1224672)

Utilizator grayshadeLaurentiu Nicola grayshade Data 31 august 2014 16:18:52
Problema Problema Damelor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <chrono>
#include <iostream>
#include <fstream>

class stopwatch
{
    std::chrono::high_resolution_clock::time_point start;

public:
    stopwatch()
        : start(std::chrono::high_resolution_clock::now())
    {
    }

    ~stopwatch()
    {
        auto duration = std::chrono::high_resolution_clock::now() - start;
        std::cerr << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << " ms" << std::endl;
    }
}; 

#define NMAX 13
using namespace std;

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

int n;

int sol[NMAX];

bool column[NMAX];

bool main_diag[2 * NMAX - 1];
bool sec_diag[2 * NMAX - 1];

int no_solutions;

void n_queens_problem(int k)
{
    if (k == n)
    {
        if (!no_solutions++)
        {
            for (int i = 0; i < n; ++i)
                g << sol[i] + 1 << " ";
            g << "\n";
        }
        return;
    }

    for (int c = 0; c < n; c++)
    {
        if (!column[c] && !main_diag[NMAX + k - c] && !sec_diag[k + c])
        {
            sol[k] = c;
            column[c] = main_diag[NMAX + k - c] = sec_diag[k + c] = true;
            n_queens_problem(k + 1);
            column[c] = main_diag[NMAX + k - c] = sec_diag[k + c] = false;
        }
    }
}

int main() {
    stopwatch sw;
    f >> n;
    n_queens_problem(0);
    g << no_solutions << "\n";
    return 0;
}