Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 14715 Accepted Submission(s): 6720
Problem 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 8
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
Source
Asia 1996, Shanghai (Mainland China)
分析:
(1)这道题非常类似于N皇后问题,使用的是深度优先搜索方法
(2)虽然说打印要求是按照顺时针和逆时针顺序打印,其实按照从小到大的*搜索顺序搜索后的结果就是符合输出顺序的。*
(3)由于是20以内的数字,所以判断质数的方法是直接打表后一个简单的循*环判断一下是否为质数*
(4)程序中mark数组是为了标记某个数字是否使用过了,num数组存储的是*数字链表的存储顺序。*
题解看注释更简单,判断没用打表
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "math.h"
using namespace std;
const int maxn = 1e2;
int num[maxn];//存一个素数环的数
int T;//多长的环
int vis[maxn];//判断有没有用过这个数,0=没有。
int m_num[21];
int ans[maxn];
void printNum(){
for( int i=1 ; i<=T-1 ; i++ ){
printf("%d ",num[i]);
}
printf("%d",num[T]);
}//不想太乱
bool isprime(int n){
if(n<2) return false;
for( int i=2 ; i<=sqrt(n) ; i++ ){
if(n%i==0) return false;
}
return true;
}//判断素数,其实打表更好
int dfs(int last,int now,int no){
if(!isprime(last+now)) return 0;//一开始就判断,不行就退出
num[no]=now;//行的话就把当前是找到第几次了的数放进对应下标的num里
if(no==T&&isprime(1+num[no])){
printNum();
cout<<endl;
return 1;
}//找到要求的这么长的了,输出。
vis[now]=1;//这个数(now)用过了,表示一下
for(int i=2 ; i<=T ; i++)
if(!vis[i]&&dfs(now,i,no+1)) break;//找到下一个可以的为止
vis[now]=0;//一圈完了,数又可以用了
return 0;
}
int main(){
int cas=1;
while(~scanf("%d",&T)){
memset(vis,0,sizeof(vis));//刚开始全部的数都可以用
num[1]=1;
printf("Case %d:\n",cas++);
for(int i=2 ; i<=T ; i++){
dfs(1,i,2);
}
cout<<endl;
}
return 0;
}