HDU 1016 Prime Ring Problem DFS
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.
Note: the number of first circle should always be 1.
![](http://acm.hdu.edu.cn/data/images/1016-1.gif)
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.
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
《此处应有空格》
这道题目就是让你全排列一个总数字为n个的素数环。
打了一个素数表然后简单的DFS直接就可以过了。
一开始跟样例输出一样,一直不知道为什么PE了,后来看讨论版,发现其实应该在每一个Case后面加空格,而不是两个Case之间有空格。
代码如下:
1 #include<cstdio> 2 #include<iostream> 3 #include<cmath> 4 #include<cstring> 5 using namespace std; 6 int n,k; 7 int num[13]={0,2,3,5,7,11,13,17,19,23,29,33,37}; 8 int check[21]; 9 bool use[21]; 10 int before; 11 bool panduan(int a) 12 { 13 for (int i=1;i<=12;++i) 14 { 15 if (a==num[i]) 16 return true; 17 } 18 return false; 19 } 20 void search(int x,int nn) 21 { 22 int t; 23 if (nn==n) 24 { 25 26 if (panduan(x+1)==true) 27 { 28 29 for(int i=1;i<n;++i) 30 printf("%d ",check[i]); 31 printf("%d\n",check[n]); 32 } 33 return; 34 } 35 for (int i=2;i<=n;++i) 36 { 37 if (use[i]==false&&panduan(i+before)==true) 38 { 39 check[nn+1]=i; 40 use[i]=true; 41 t=before; 42 before=i; 43 search(i,nn+1); 44 check[nn+1]=0; 45 use[i]=false; 46 before=t; 47 } 48 } 49 } 50 int main(){ 51 k=0; 52 while(scanf("%d",&n)!=EOF) 53 { 54 55 for(int i=1;i<=n;++i) 56 { 57 check[i]=0; 58 use[i]=false; 59 } 60 use[1]=true; 61 check[1]=1; 62 int xx=1; 63 k++; 64 65 printf("Case %d:\n",k); 66 if(xx!=n) 67 { 68 before=1; 69 search(1,1); 70 }else printf("1"); 71 printf("\n"); 72 } 73 return 0; 74 }