HDU 1016 Prime Ring Problem HDU 1016 Prime Ring Problem 素数环

HDU 1016 Prime Ring Problem 素数环
Problem 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

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int a[25],res[25],bk[25],n,top=0;
void dfs(int nub)
{
    if(nub==n)
    {
        if(a[res[nub-1]+res[0]]) return;
        else
        {
            for(int j=0; j<nub; j++)
            {
                if(j==0)
                    cout<<res[j];
                else
                    cout<<' '<<res[j];
            }
            cout<<endl;
            return;
        }
    }
    else
    {
        for(int i=2; i<=n; i++)
        {
            if(!a[i+res[nub-1]]&&bk[i]==0)
            {
                res[nub]=i;
                bk[i]=1;
             //   cout<<res[nub]<<endl;
                dfs(nub+1);
                bk[i]=0;
            }
        }
    }
    return;
}
int main()
{
    int t=0;
    for(int i=2; i<24; i++)
    {
        if(!a[i])
        {
            for(int j=i*2; j<24; j+=i)
                a[j]=1;
        }
    }
    while(cin>>n)
    {   t++;
        top=0;
        memset(bk,0,sizeof(bk));
        printf("Case %d:\n",t);
        res[0]=1;
        dfs(1);
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/stanmae/article/details/80273523