HDU 1016 Prime Ring Problem

来源:互联网 发布:mysql 模糊搜索 编辑:程序博客网 时间:2024/04/27 18:34

 

题意:给你一个N,要你把1->N这N个数组成一个环(第一个放的必须是1),要求是相邻的两个数加起来必须是素数( 素数环 ),而且最后一个和第一个同样要保持这个性质

 

思路: 记忆化搜索

 

                                  Prime Ring Problem

                                             Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
                                             Total Submission(s): 18093    Accepted Submission(s): 8105


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

 


 

#include <stdio.h>#include <algorithm>#include <stdlib.h>#include <string.h>#include <math.h>using namespace std;int n,l;int num[30];bool visit[30]; bool flag;               //标记是否找到正解 int judge( int x ){for( int i=2 ; i<sqrt( (double)x )+1 ; i++ )if( x % i == 0 )return false;return true;}void DFS( int st , int count ){visit[st] = true;if( count == n ){           //1到N全部放到了环里 if( judge( st + 1 ) ){//printf("enter\n");flag = true;   //搜到了结果 }return ;}for( int i=1 ; i<=n ; i++ ){if( !visit[i] && judge( st + i ) ){num[ count+1 ] = i;//printf("%d\n",i);DFS( i , count+1 );if( flag ){for( int j=1 ; j<=n ; j++ )printf( j==n ? "%d\n" : "%d " , num[j] );visit[i] = false;flag = false;}elsevisit[i] = false;}}}int main( ){int cas = 1;while( scanf("%d",&n) == 1 ){memset( visit , false , sizeof(visit) ); flag = false;//l = 0;printf("Case %d:\n",cas++);num[1] = 1;DFS( 1 , 1 );printf("\n");}return 0;}