Q-17

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
 

题意:

n个数从1到n,构成一个环形,保证相邻的两个数和为素数,找到所有的可能

分析:

其实用dfs就可以,要特殊处理第一个数和第n个数

代码:

  1. #include<iostream>  
  2. #include<cstring>  
  3. #include<string>  
  4. using namespace std;  
  5. int a[25],b[25],n,ss[40];  
  6. void dfs(int k)  
  7. {  
  8.     int i,j;  
  9.     if(k==n){  
  10.         if(ss[a[k]+a[1]]==0)  
  11.         {  
  12.             for(j=1;j<n;j++)  
  13.             cout<<a[j]<<" ";  
  14.             cout<<a[n]<<endl;  
  15.         }  
  16.         return;  
  17.     }  
  18.     for(i=2;i<=n;i++)  
  19.     {  
  20.         if(b[i]==0)  
  21.         {  
  22.             if(ss[i+a[k]]==0&&k<n){  
  23.                 b[i]=1;  
  24.                 a[k+1]=i;  
  25.                 dfs(k+1);  
  26.             }  
  27.             b[i]=0;  
  28.         }  
  29.     }  
  30. }  
  31. int main()  
  32. {  
  33.     int i,j;  
  34.     ss[1]=1;  
  35.     a[1]=1;  
  36.     for(i=2;i<40;i++)  
  37.     {  
  38.         if(ss[i]==0)  
  39.         {  
  40.             for(j=i+1;j<40;j++)  
  41.             if(j%i==0)  
  42.             ss[j]=1;  
  43.         }  
  44.     }  
  45.     i=1;  
  46.     while(cin>>n&&n)  
  47.     {  
  48.         memset(b,0,sizeof(b));  
  49.         cout<<"Case "<<i<<":"<<endl;  
  50.         if(n==1)cout<<1<<endl;  
  51.         else  
  52.         dfs(1);  
  53.         cout<<endl;  
  54.         i++;  
  55.     }  
  56. }  



阅读更多

没有更多推荐了,返回首页