1105:素数圆环

#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;

int ans[21]={0},tot=0;
bool a[21]={0};
void print(int d)
{
	tot++;
	if(ans[1]==1)
	{for(int i=1;i<=d;i++)
		cout<<ans[i]<<" ";
	cout<<endl;
	}

}

bool isprime(int x1,int x2)
{
	int i=x1+x2;
	int f;
	for(f=2;f<=sqrt(i);f++)
		if(i%f==0) return false;
		return true;
}

void search(int t,int d)
{
	for(int i=1;i<=d;i++)
	{
		if(a[i]==false && isprime(ans[t-1],i))
		{
			ans[t]=i;
	    	a[i]=true;
			if(t==d && isprime(ans[1],ans[d])) {print(d);}
			else
			search(t+1,d);
			a[i]=false;
		}
	}
}

int main()
{

int num;
int i=1;
while(cin>>num)
{
	cout<<"Case "<<i++<<":"<<endl; 
search(1,num);
cout<<endl;}
return 0;
}

题目描述

如图所示为一个由n个圆圈构成的圆环。将自然数1,2,...,n放入圆圈内,并且要求任意两个相邻的圆圈内的数字之和为素数。请问给你圆圈数,你能给出放置自然数的所有正确方案吗?

注意:圆圈中的数字一定是从1开始的,并且连续不重复。

输入格式

输入包含多组测试数据。每组输入占一行,为整数n(0<n<20),表示圆圈数。

输出

对于每组输入,输出所有正确的方案,按字典序从小到大排序。每组输出后输出一个空行。具体输出格式见输出样例。
注意:只能按照顺时针方向放置数字。

样例输入

6
8

样例输出

Case 1:
1 4 3 2 5 6
1 6 5 2 3 4

Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2


猜你喜欢

转载自blog.csdn.net/u014775977/article/details/42874577