vsooda的专栏

新博客: http://vsooda.github.io github: https://github.com/vsooda

XMU 1098 N皇后
#include<iostream>
#include<cmath>
#include<time.h>
using namespace std;
const unsigned long maxshort=65536L;
const unsigned long multiplier=1194211693L;
const unsigned long adder=12345L;
class RandomNumber
{
private:
	unsigned long randSeed;
public:
	RandomNumber(unsigned long s=0);
	unsigned short Random(unsigned long n);
	double fRandom(void);
};

RandomNumber::RandomNumber(unsigned long s)
{
	if(s==0)
		randSeed=time(0);
	else 
		randSeed=s;
}
unsigned short RandomNumber::Random(unsigned long n)
{
	randSeed = multiplier * randSeed + adder;
	return (unsigned short) ((randSeed>>16) % n);
}
double RandomNumber::fRandom(void)
{
	return Random(maxshort)/double(maxshort);
}
class Queen
{
	friend bool nQueen(int);
private:
	bool place(int k);
	bool backtrack(int t);
	bool queenLV(int stopLV);
	int n ,*x,*y;
};

bool Queen::place(int k)
{
	for(int j=1;j<k;j++)
		if((abs(k-j)==abs(x[j]-x[k])) || (x[j]==x[k]))
			return false;
	return true;
}

bool Queen::backtrack(int t)
{
	if(t>n)
	{
		for(int i=1;i<=n;i++)
			y[i]=x[i];
		return true;
	}
	else
		for(int i=1;i<=n;i++)
		{
			x[t]=i;
			if(place(t) && backtrack(t+1))
				return true;
		}
		return false;
}

bool Queen::queenLV(int stopLV)
{
	RandomNumber rnd;
	int k=1;
	int count=1;
	while((k<= stopLV ) && (count>0))
	{
		count=0;
		for(int i=1;i<=n;i++)
		{
			x[k]=i;
			if(place(k))
				y[count++]=i;
		}
		if(count>0)
			x[k++]=y[rnd.Random(count)];
	}
	return (count>0);

}

bool nQueen(int n)
{
	Queen X;
	X.n=n;
	int *p=new int[n+1];
	int *q=new int[n+1];
	for(int i=0;i<=n;i++)
	{
		p[i]=0;
		q[i]=0;
	}
	X.y=p;
	X.x=q;
	int stop=5;
	if(n<5)
		stop=1;
	if(n>15)
		stop=n-15;
	bool found = false;
	while(!X.queenLV(stop));
	if(X.backtrack(stop+1))
	{
		for(int i=1;i<=n;i++)
			cout<<i<<" "<<p[i]<<endl;
		found = true;
	}
	delete[] p;
	delete[] q;
	return found;
}

int main()
{
	int n;
	cin>>n;
	while(!nQueen(n));
	return 0;
}

阅读更多
文章标签: random delete class
个人分类: xmu
想对作者说点什么? 我来说一句

算法设计与分析

2013年12月22日 1KB 下载

计算智能历年卷

2018年01月25日 19.59MB 下载

没有更多推荐了,返回首页

不良信息举报

XMU 1098 N皇后

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭