codevs 1031 质数环

题目描述 Description

一个大小为N(N<=17)的质数环是由1到N共N个自然数组成的一个数环,数环上每两个相邻的数字之和为质数。如下图是一个大小为6的质数环。为了方便描述,规定数环上的第一个数字总是1。如下图可用1 4 3 2 5 6来描述。若两个质数环,数字排列顺序相同则视为本质相同。现在要求你求出所有本质不同的数环。

输入描述 Input Description


只有一个数N,表示需求的质数环的大小。如:

输出描述 Output Description

每一行描述一个数环,如果有多组解,按照字典序从小到大输出。如:

样例输入 Sample Input

6

样例输出 Sample Output

1 4 3 2 5 6

1 6 5 2 3 4

数据范围及提示 Data Size & Hint
n<=17
 
 
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
using namespace std;
	int n,f[20]={0},a[20];
int zh(int x,int y)
{
	int r=x+y;
	for (int i=2;i<=ceil(sqrt(r));i++)
	  if (r%i==0) return 0;
	return 1;
}
void print()
{
	for (int i=1;i<=n;i++)
	  cout<<a[i]<<' ';
	cout<<endl;
}
int xs(int t)
{
	{
	for (int i=2;i<=n;i++)
	  if ((! f[i])&&zh(a[t-1],i)) 
	    {
	    	 a[t]=i;
	    	 f[i]=1;
	    	 if (t==n&&zh(a[n],a[1]))print(); 
			 	 else xs(t+1);
			 	f[i]=0;//回溯 
		}

}
}
int main()
{

	f[1]=1;
	a[1]=1;
	cin>>n;
	xs(2);
	return 0;
}

  

I'm so lost but not afraid ,I've been broken and raise again
原文地址:https://www.cnblogs.com/sjymj/p/5244056.html