1. 程式人生 > >【HDU】1016Prime Ring Problem(dfs+素數)

【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;
}