UVA 524 Prime Ring Problem dfs

来源:互联网 发布:java ee eclipse使用 编辑:程序博客网 时间:2024/06/07 01:06

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<stdio.h>#include<string.h>using namespace std;int a[35],b[17],c[17],n;void su(){    a[3]=1;a[5]=1;a[7]=1;a[11]=1;a[13]=1;    a[17]=1;a[19]=1;a[23]=1;a[29]=1;a[31]=1;}int dfs(int pre,int post,int flag){    if(a[pre+post]==0)        return 0;    c[flag]=post;    if(flag==n&&a[post+1])    {        cout<<"1";        for(int i=2;i<=n;i++)            cout<<" "<<c[i];        cout<<endl;        return 1;    }    b[post]=0;    for(int i=2;i<=n;i++)        if(b[i]!=0&&dfs(post,i,flag+1))            break;    b[post]=1;    return 0;}int main(){    int kase=0;    while(scanf("%d",&n)!=EOF)    {    if(kase!=0)cout<<endl;        cout<<"Case "<<++kase<<":"<<endl;        if(n==1)        {            cout<<"1"<<endl<<endl;            continue;        }        memset(a,0,sizeof(a));        su();        for(int i=1;i<=n;i++)        {            b[i]=i;        }        c[1]=1;        for(int i=2;i<=n;i++)        {            dfs(1,i,2);        }    }}

0 0