这道题目搞得我老郁闷了,首先是DFS的构造,是通过2数之和来DFS的.接着的话对于边界条件1,是不输出的,而这个我是没考虑到的,1是不输出的!!!!!!!!!!!!!!!!!!!!!!!!!!!!!接着通过奇偶数分析可以更快
Status | In/Out | TIME Limit | MEMORY Limit | Submit Times | Solved Users | JUDGE TYPE |
---|
| stdin/stdout | 10s | 8192K | 1339 | 393 | Standard |
A ring is composed of n circles as shown in diagram. Put natural numbers 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 <= 16)
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.
You are to write a program that completes above process.
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
This problem is used for contest: 102
Submit / Problem List / Status / Discuss
#include<iostream> //冲刺。AIBERT
#define MAXN 41
bool p[MAXN],visit[17];//P是用来记录MAXN内的素数,VISIT是用来记录1~N里面的数字是否被使用
int circle[17],n; //用来储存每位上的数字
void prime()
{
memset(p,true,sizeof(p)); //全部初始化为TRUE
p[1]=false;
for(int i=2;i<=16;i++)
for(int j=2;i*j<=MAXN;j++)
p[i*j]=false;
}
void dfs(int c,int depth)
{
if(depth==n && p[circle[1]+circle[n]] ) //如果到了第N层并且满足第N个和第一个的和为质数
{
for(int i=1;i<=n-1;i++)
printf("%d ",circle[i]);
printf("%d/n",circle[n]);
}
for(int i=c+2;i<=MAXN;i++) //I为两个数字之和,是在C+2和MAXN之间 ,因为1已经被使用
if(i-c<=n && p[i] && visit[i-c])//I-C在N范围内,P[I]表示两数之和为质,并且数字未被使用
{
circle[depth+1]=i-c;
visit[i-c]=false;
dfs(i-c,depth+1);
visit[i-c]=true;
}
}
int main()
{
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
int count=1;
prime();
while(scanf("%d",&n)!=EOF)
{
printf("Case %d:/n",count++); //COUNT是用来记录CASE的序号
if(n!=1&&n%2!=1)
{
memset(visit,true,sizeof(visit)); //初始化VISIT数组全为TRUE
visit[1]=false;circle[1]=1; //第一个点为1,则VISIT[1]为FALSE,第一个点为一
dfs(1,1); //前面的一表示前面这个结点植为1,在第一层
}
printf("/n");
}
return 0;
}