Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 29284 Accepted Submission(s): 13047
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
Note: the number of first circle should always be 1.
You are to write a program that completes above process.
Print a blank line after each case.
6 8
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
给你一个数N。让你求在一到N之间的整数,是否相邻两个能组成素数,如能能则输出组合方式。
一道经典的DFS搜索问题,这种问题很难用文字表达清楚,我尽量吧。
代码:
#include <stdio.h>
#include <string.h>
int vis[50]; //用来标记一个数是否被用过。
int a[50]; // 用来存放可行的数。
int cc;
int n;
int cccc=0;
bool is_sushu(int b)
{
int i;
for(i=2;i*i<=b;i++)
{
if(b%i==0)
return false;
}
return true; //素数判断。
}
void dfs(int num) //num是填入的第一个数。
{
if(num==n &&is_sushu(a[0]+a[n-1])) //如果num==n则输出,
{
for(cc=0;cc<n;cc++)
{
if(cc!=n-1)
printf("%d ",a[cc]);
else
printf("%d\n",a[cc]);
}
}
else
{
int i; //这个int i要定义在这里,很重要。
for(i=2;i<=n;i++) //从2开始,因为题目说过,第一个数一定是1.
{
if(vis[i]==0 &&is_sushu(a[num-1]+i)) //如果这个数没被用过,并且上一个数加这个数为素数
{
a[num]=i;//将这个数存入数组。
vis[i]=1; //令它为一。表示用过。
dfs(num+1); //继续填数。
vis[i]=0; //回溯。
}
}
}
}
int main()
{
while(~scanf("%d",&n))
{
printf("Case %d:\n",++cccc);
memset(vis,0,sizeof(vis));
a[0]=1; //第一个数为一。
dfs(1); // 填数。
printf("\n");
}
}