【HDU】1016Prime Ring Problem(dfs+素数)

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 68225    Accepted Submission(s): 29217


 

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

 

Source

Asia 1996, Shanghai (Mainland China)

 

Recommend

JGShining   |   We have carefully selected several similar problems for you:  1010 1241 1312 1072 1242 

题目大意:给出一个数N,表示从1~N的区间内,要求输出每每相邻的两个数的和都是素数的这样的环,环上的数的数量为N就是这些数都要用上,并要求将所有的可能的这样的环输出。

 思路:首先要得到从1~N所有的素数,其次就是dfs求环的状态了,比较简单的一个大dfs吧,还有就是不要忘记最后面的结尾的那个和开头的那个数也要满足加和为素数的性质,因为我们找的是环。详情看代码吧。

代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define maxn 101
using namespace std;

int n;
int prime[maxn];
int ans[maxn],vis[maxn];
void init()
{
    memset(prime,0,sizeof(prime));
    for(int i=2;i<maxn;i++)
    {
        if(!prime[i])
        {
            for(int j=i*i;j<maxn;j+=i)
                prime[j]=1;
        }
    }
}

void dfs(int pos)
{
    if(pos==n)
    {
        if(prime[ans[0]+ans[n-1]]==0)
        {
            printf("%d",ans[0]);
            for(int i=1;i<n;i++)
            {
                printf(" %d",ans[i]);
            }
            printf("\n");
        }
    }
    else
    {
        for(int i=1;i<=n;i++)
        {
            if(vis[i]==0&&!prime[ans[pos-1]+i])
            {
                vis[i]=1;
                ans[pos]=i;
                dfs(pos+1);
                vis[i]=0;
            }
        }
    }
}

int main()
{
    init();
    int kase=1;
    while(scanf("%d",&n)==1)
    {
        printf("Case %d:\n",kase++);
        memset(vis,0,sizeof(vis));
        ans[0]=1;
        vis[1]=1;
        dfs(1);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wentong_Xu/article/details/84312679
今日推荐