Q

来源:互联网 发布:淘宝乐高日本代购 编辑:程序博客网 时间:2024/06/02 10:43

Description
A ring is compose of n circles as shown in diagram. Put natural number 1, 2, ..., n into each circle separately, and the sum of numbers in two adjacent circles should be a prime. 


Note: the number of first circle should always be 1. 




 
Input
n (0 < n < 20). 
 
Output
The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order. 


You are to write a program that completes above process. 


Print a blank line after each case. 
 
Sample Input
 6

 
Sample Output
 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 

解题思路:

做的很顺利的一题,几乎没改就过了,

代码:

#include<iostream>#include<cmath>#include<cstring>using namespace std;int n;int cir[21]; //记录每个位置的数int t[21]; //存放数的使用状况bool ok(int a,int b)   //判断数素{int x=a+b;int k=2;while(k<=sqrt(x)&&x%k!=0) k++;if(k>sqrt(x)) return true;else return false;}void print() //输出一种方案{for(int i=1;i<n;i++)cout<<cir[i]<<" ";cout<<cir[n]<<endl;}void solve(int m) //找第m个位置的数{for(int i=2;i<=n;i++){if(ok(cir[m-1],i)&&!t[i])//与前一个数和为数素,且此数未用过{cir[m]=i; //保存当前位置数t[i]=1;  //此数已用if(m==n&&ok(1,cir[m])) //找齐n个数,且首尾数和为素数{print();}else solve(m+1); //继续找下一位置t[i]=0;  //恢复状态}}}int main(){int cas=0;cir[1]=1;while(cin>>n){memset(t,0,sizeof(t));t[1]=1;cas++;cout<<"Case "<<cas<<":"<<endl;solve(2);cout<<endl;}return 0;}


0 0
原创粉丝点击