Cod sursa(job #1231453)

Utilizator daniel.amarieiDaniel Amariei daniel.amariei Data 20 septembrie 2014 18:14:06
Problema Problema Damelor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include <fstream>
using namespace std;

#define ABS(x) ((x) >= 0 ? (x) : -(x))
int n, s, V[14];

ifstream ifs("damesah.in");
ofstream ofs("damesah.out");

	
void backtrack(int q)
{
	if (q > n)
	{
		++s;
		
		if (s == 1)
		{
			// Print first solution
			for (int i = 1; i <= n; ++i)
			{
				ofs << V[i] << " ";
			}
			
			ofs << "\n";
		}
	} 
	else
	{
		for (int j = 1; j <= n; ++j)
		{
			bool is_safe = true;
			for (int i = 1; i < q; ++i)
			{
				if (V[i])
				{
					if (j == V[i]) is_safe = false; 
					if ((q - i) == ABS(j - V[i])) is_safe = false;
				}
			}
			
			if (is_safe)
			{
				V[q] = j;
				backtrack(q+1);
				V[q] = 0;
			}
		}
	}
}


int main()
{	
	ifs >> n;
	
	backtrack(1);
	ofs << s;
	
	return 0;
}