1. 程式人生 > >Prime Ring Problem 經典素數環

Prime Ring Problem 經典素數環

str anti 兩個 row num lan 輸出 idt class

Prime Ring Problem

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.

技術分享

Inputn (0 < n < 20).
OutputThe 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組成一個素數環,相鄰兩個數的和為素數。
      首先偶數(2例外,但是本題不會出現兩個數的和為2)不是素數,
      所以素數環裏奇偶間隔。如果n是奇數,必定有兩個奇數相鄰的情況。
      所以當n為奇數時,輸出“No Answer”。
      當n == 1時只1個數,算作自環,輸出1
      所有n為偶數的情況都能變成奇偶間隔的環-----所以都有結果。


#include<stdio.h>
#include<string.h>
int n,c=0,i;
int a[25],b[25];
int jo(int a)
{
    return a%2==0?0:1;
}
int prime[40]={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};
void dfs(int step)
{
    int i;
    if(step>n&&prime[a[1]+a[n]]){
        for(i=1;i<=n;++i){
            
if(i==1) printf("%d",a[i]); else printf(" %d",a[i]); } printf("\n"); return; } if(jo(a[step-1])){ for(i=2;i<=n;i+=2){ if(!b[i]&&prime[a[step-1]+i]){ b[i]=1; a[step]=i; dfs(step+1); b[i]=0; } } } else{ for(i=3;i<=n;i+=2){ if(!b[i]&&prime[a[step-1]+i]){ b[i]=1; a[step]=i; dfs(step+1); b[i]=0; } } } } int main() { while(~scanf("%d",&n)){ memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); a[1]=1;b[1]=1; if(n==1) printf("Case %d:\n1\n\n",++c); else if(!jo(n)){ printf("Case %d:\n",++c); dfs(2); printf("\n"); } } return 0; }

Prime Ring Problem 經典素數環