524 - Prime Ring Problem

来源:互联网 发布:抗战中日伤亡真实数据 编辑:程序博客网 时间:2024/04/29 00:29

A ring is composedof n (even number) circles as shown in diagram. Put natural numbers into eachcircle separately, and the sum of numbers in two adjacent circles should be aprime.


Note: the number of first circle should always be 1.

Input 

n (0 < n <=16)

Output 

The output formatis shown as sample below. Each row represents a series of circle numbers in thering beginning from 1 clockwise and anticlockwise. The order of numbers mustsatisfy the above requirements.

Note: There shouldbe a blank line between two successive output.
You are to write a program that completes above process.

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

代码:

#include<iostream>

#include<cstring>

using namespacestd;

 

int n;

inta[100],vis[100];

 

void dfs(int cur);

bool prime(int n);

 

int main()

{

    int kase=1;

    while(cin>>n)

    {

        if(kase!=1)

        {

            cout<<endl;

        }

        memset(vis,0,sizeof(vis));

        a[0]=1;

        cout<<"Case"<<kase++<<":\n";

        dfs(1);

    }

    return 0;

}

 

void dfs(int cur)

{

    if(cur==n&&prime(a[0]+a[n-1]))

    {

        for(int i=0; i<n-1; i++)

        {

            cout<<a[i]<<"";

        }

        cout<<a[n-1]<<endl;

    }

    else

    {

        for(int i=2; i<=n; i++)

        {

            if(!vis[i]&&prime(i+a[cur-1]))

            {

                a[cur]=i;

                vis[i]=1;

                dfs(cur+1);

                vis[i]=0;

            }

        }

    }

}

 

bool prime(int n)

{

    for(int i=2; i*i<=n; i++)

    {

        if(n%i==0)

        {

            return false;

        }

    }

    return true;

}

0 0
原创粉丝点击