HDU 1016 Prime Ring 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
 
     题意:给一个数n,用1到n中的所有数围成一个环,并且每相邻的两个数相加为素数,问这样的环有多少个,并输出每个环。每个从1开始输出。
    这题用dfs搜索,每次从1开始搜。一要如何搜,那就看代码吧。
 
 
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,v[25],a[25];
int ssb[100],zj[100],pn;
void f()
{
    int i,j;
    zj[0]=1;
    zj[1]=1;
    pn=0;
    for (i=2;i<=100;i++)
    {
        if (zj[i]==0) ssb[pn++]=i;
        for (j=0;j<pn;j++)
        {
            if (i*ssb[j]>100) break;
            zj[i*ssb[j]]=1;
            if (i%ssb[j]==0) break;
        }
    }
}
void dfs(int x,int k)
{
    int i,j;
    for (i=2;i<=n;i++)
    {
        if (!v[i]&&zj[i+x]==0)
        {
            v[i]=1;
            a[k+1]=i;
            if (k+1==n)
            {
                if (zj[1+a[n]]==0){
                for (j=1;j<n;j++) printf("%d ",a[j]);
                printf("%d
",a[n]);}
            }
            dfs(i,k+1);
            v[i]=0;
        }
    }
}
int main()
{
    int cut=1;
    a[1]=1;
    memset(zj,0,sizeof(zj));
    f();
    while (~scanf("%d",&n))
    {
        printf("Case %d:
",cut);
        cut++;
        memset(v,0,sizeof(v));
        dfs(1,1);
        printf("
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/pblr/p/4696365.html