Prime Ring Problem
Time Limit : 4000/2000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 13 Accepted Submission(s) : 9
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)
总结:
此题属于深搜题,刚一接触时,准备先用全排列回溯法把所有的情况列出来再一一筛选满足条件的输出,可是有个问题我没注意到啊,一开始没有优化导致tle,而且全排列回溯法输出的并不是字典序,所以后来即使优化了还是wa,后来再网上看到全排列的字典序方法,而且是非递归的,蛮不错。
(
全排列的字典序法
算法思想:
例子:839647521的下一个排列.
从最右开始,找到第一个比右边小的数字4,再从最右开始,找到4右边比4大的数字5,交换4、5,此时5右边为7421,倒置为1247,即得下一个排列:839651247.用此方法写出全排列的非递归算法如下:
)
但是这道题我觉得还是、深搜好,不会去判断很多不需要的排列。
思想总结:
a[25]存放的是1-25,作为排列用;
flag[25]标记有哪些数还未被使用,dfs之前令flag[j]=1,dfs之后回溯令flag[j]=0;
(
flag[j]=1;
DFS(i+1);
flag[j]=0;
)
还有一个数组存放结果 :ans[25];(即排列);
注:int a[25],flag[25],ans[25];全为全局变量。#include<cstdio>
#include<memory>
using namespace std;
int a[25],flag[25],ans[25],c[50];
int n;
void DFS(int i)
{
if(i==n&&c[ans[0]+ans[n-1]])
{
for(int k=0;k<n;k++)
{
if(!k)printf("%d",ans[k]);
else printf(" %d",ans[k]);
}
printf("\n");
return ;
}
for(int j=1;j<n;j++)
{
if(!flag[j])
{
if(c[ans[i-1]+a[j]])
{
ans[i]=a[j];flag[j]=1;
DFS(i+1);
flag[j]=0;
}
else continue;
}
}
}
int main()
{
int i,j,t=1;
for(i=0;i<25;i++) a[i]=i+1;
memset(c,0,sizeof(c));
c[2]=c[3]=c[5]=c[7]=c[11]=c[13]=c[17]=c[19]=c[23]=c[29]=c[31]=c[37]=c[39]=1;
ans[0]=1;
while(scanf("%d",&n)!=EOF)
{
memset(flag,0,sizeof(flag));
printf("Case %d:\n",t++);
DFS(1);
printf("\n");
}
return 0;
}