|
Prime Ring ProblemTime Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 24091 Accepted Submission(s): 10738
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
Sample Output
Source
Recommend
|
题意:就是给一个数n,然后从[1,n]中找出若干个序列输出,序列要求满足的条件:按顺序构成一个环,然后要求环上相邻的两个数相加和为素数。
#include<cstdio>
#include<cstring>
int prime[40]={0,1,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0},n; //数组表示哪个数是素数,这个网上抄的
int used[40],s[40];
void dfs(int x)
{
int i;
if( x==n && prime[s[x-1]+s[0]] )//表示环上已经有n个数,并且最后一个数和第一个数的和为素数。
{
for(i=0;i<x-1;i++)
printf("%d ",s[i]);
printf("%d\n",s[i]);//输出符合条件的环。
}
else
{
for(i=2;i<=n;i++)
{
if(used[i]==0)表示这个数还没有用过
{
if(prime[i+s[x-1]])//表示相邻的两个数相加和为素数,加到数组中,并进行下一层dfs。
{
used[i]=-1;//把这个数标记为已经用过。
s[x++]=i;//把这个数加到数组里。
dfs(x);
used[i]=0;//如果搜索不成功,则返回这一层,然后继续执行下面的语句,并将数i还原为没有用过的状态。
x--;//还原,表示数组中现在有 x-- 个数。
}
}
}
}
}
int main()
{
int i=0;
while(scanf("%d",&n)!=EOF)
{
i++;
printf("Case %d:\n",i);
memset(used,0,sizeof(used));
s[0]=1;
dfs(1);
printf("\n");
}
return 0;
}