题目1016: Prime Ring Problem

来源:互联网 发布:2017淘宝内容营销 编辑:程序博客网 时间:2024/05/16 11:58
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
68
 


 

Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
 


 

Source
Asia 1996, Shanghai (Mainland China)
 


 

Recommend
JGShining
 


 

/*********************************  *    日期:2013-3-14 *    作者:SJF0115  *    题号: HDU 题目1016: Prime Ring Problem *    来源:http://acm.hdu.edu.cn/showproblem.php?pid=1016 *    结果:AC  *    来源:Asia 1996, Shanghai (Mainland China)  *    总结: **********************************/#include<stdio.h>#include<string.h>int prime[] = {0,0,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,0};int visited[21];  int value[21];int n;void DFS(int step){int i;//最后一个数还需要和1判断一下相加是否是素数if(step == n+1){if(prime[value[step - 1] + 1]){//输出素数环for(i = 1;i <= n;i++){printf("%d%c",value[i],i==n?'\n':' ');}}}else{for(i = 2;i <= n;i++){//该数据没有使用过并且与前一个数相加为素数if(!visited[i] && prime[i + value[step-1]]){//标记已访问visited[i] = 1;value[step] = i;DFS(step+1);visited[i] = 0;}}}}int main(){int caseNum = 1;    while(scanf("%d",&n) != EOF){memset(visited,0,n);printf("Case %d:\n",caseNum);//素数环的第一个数永远都是1value[1] = 1;DFS(2);printf("\n");caseNum ++;}return 0;}