1. 原题
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 83554 Accepted Submission(s): 34353
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)
Recommend
JGShining | We have carefully selected several similar problems for you: 1010 1241 1312 1072 1242
2.题目解析
3.代码
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
int circle[21] = {0};//初始化
bool tell[21] = {false};//初始化
void circle_print(int n){
int i;
for (i = 1; i < n; i++)printf("%d ",circle[i]);
printf("%d\n",circle[i]);
}//按照格式打印出数据
bool isprime(int x1, int x2){
int i = x1 + x2,f;
for (f = 2; f <= sqrt(i); f++)
if (i % f == 0)return true;
return false;
}//前一位和当前位置之和是否为素数
void next_search(int n,int t){//n表示搜索的环数
int i;
for (i = 2; i <= n; i++){
if (tell[i] == false && isprime(circle[t - 1], i)==false){
//数字i没有被使用 且 与前一直数字之和为素数
circle[t] = i;//符合第t位置上面的值,给第t位赋值
tell[i] = true;//表示第i个位置已经使用
if (t == n && isprime(circle[1], circle[n])==false)circle_print(n);
//如果已经搜到环的最后一个数字且最后最后一位与第一位之和为素数,那么就先输出
else next_search(n,t + 1);
//继续搜索第t+1的位置
tell[i] = false;
//从t+1的那个房间返回到t的这号房间,标识着要开始重新赋值,这组数据已经用过了
}
}
}
int main() {
int n,num=1;
circle[1]=1;
while(scanf("%d",&n)!=EOF){printf("Case %d:\n",num++);next_search(n,2);printf("\n");}
}
结语:其实做这个题的时候也是碰巧,随便瞎写,就想一定要把这个题目给做出来(一开始我也没有想到回溯)
只要自己肯努努力,一切终将成功