Prime Ring Problem HDU - 1016

来源:互联网 发布:《南风知我意》 编辑:程序博客网 时间:2024/06/01 15:51
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
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
题目大意:就是给定几个数,然后必须以1开头,相邻两个数之和必须是素数。

思路;因为最大只有20个数,所以可以用回溯法,注意下递归的边界就可以了,另外判断是不是素数,因为这里的数比较下,可以自己写个函数判断,但是因为之前刚学了筛数法,所以我尝试直接打表素数。

下面是ac代码

#include<cstdio>
#include<string.h>
int vis[20],n,ss[50],a[25];
void sushudabiao()
{
    ss[1]=0;
    for(int i=2;i<=40;i++)
    {
        if(!ss[i])
        {
            for(int j=i*2;j<=40;j+=i)
            {
                ss[j]=1;
            }
        }
    }
}
void dfs(int x)
{
    if(x>n)
    {
        if(!ss[a[x-1]+1])
        {
        for(int j=1;j<=n;j++)
        {
            printf("%d%c",a[j],j==n?'\n':' ');
        }
        }
        return;
    }
    for(int i=2;i<=n;i++)
    {
        a[x]=i;
        if(!ss[a[x]+a[x-1]]&&!vis[i])
        {
            vis[i]=1;
            dfs(x+1);
            vis[i]=0;
        }
    }
}
int main()
{
    int t=1;
    sushudabiao();
    while(~scanf("%d",&n))
    {
        printf("Case %d:\n",t++);
        a[1]=1;
            memset(vis,0,sizeof(vis));
            dfs(2);
            printf("\n");
    }
    return 0;


}

0 0
原创粉丝点击