uva 724 Prime Ring Problem

来源:互联网 发布:一入淘宝深似海下一句 编辑:程序博客网 时间:2024/05/18 09:30

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers $1, 2, \dots, 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 <= 16)

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.


You are to write a program that completes above process.

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 <iostream>#include <cstdio>#include <cstring>#include <cmath>using namespace std;int vis[18],a[18],isprime[36];int n;int tot=0;void make_prime(){  int tmp=sqrt(2*n+0.5);    memset(isprime,0,sizeof(isprime));    for(int i=2;i<=tmp;i++)    if(!isprime[i])    for(int j=i*2;j<=2*n;j+=i)    isprime[j]=1;}void dfs(int cnt){    if(cnt==n && !isprime[a[0]+a[n-1]])     {         for(int i=0;i<n;i++)          cout<<a[i]<<" ";          cout<<endl;     }      else    for(int i=2;i<=n;i++)      if(!vis[i] && !isprime[i+a[cnt-1]])      {          a[cnt]=i;          vis[i]=1;          dfs(cnt+1);          vis[i]=0;      }}int main(){    while(~scanf("%d",&n)&&n)    {        tot++;         cout<<"Case "<<tot<<":\n";        memset(vis,0,sizeof(vis));        memset(a,0,sizeof(a));        make_prime();        a[0]=1;        dfs(1);    }    return 0;}


0 0
原创粉丝点击