Prime Ring Problem DFS

Prime Ring Problem

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 3   Accepted Submission(s) : 3

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

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


解题思路:
从1~N,N个数,围成一个环,要求相邻的两个数和为质数。当然,第一个数要求固定为1。搜索?搜索!深搜!!
首先考虑数据结构,即用什么来存储当前的数据环,考虑用数组。DFS的 本质就是递归,搜索无效返回的时候就要
回溯,体现在本题中就牵涉到一个数组的值得问题,即visit[21]数组,最初只有visit[0]被标记为1,其他全为0,在每一次
递归调用前先将当前位置所填充的数标记为1,在每一次回溯时将visit标记为0。那么,还有可以优化的地方吗?答案是肯定的。
在判断素数的时候我们可以用数组来标记,这样的一对一映射十分快。啦啦啦。。。。


#include
#include


using namespace std;


int a[40];
int visited[20];
int b[20];
int n;
int i,j,k;


int prime(int i)
{
    int j;
    bool b1=0;
    for(j=2;j<=i/2;j++)
    {
        if(i%j==0)
        {
            b1=1;
            break;
        }
    }
    if(b1==1)
        return 0;
    else return 1;
}


void dfs(int x)
{
    if(x>=n && a[b[x-1]+1])
    {
        cout<         for(int i=1;i         {
            cout<<" "<         }
        cout<     }
    else
    {
        for(int j=2;j<=n;j++)
        {
            if(a[b[x-1]+j] && !visited[j])
            {
                b[x]=j;
                visited[j]=1;
                dfs(x+1);
                visited[j]=0;
            }
        }
    }
}


int main()
{
    for(i=0;i<40;i++)
    {
        if(prime(i)==1)
        {
            a[i]=1;
        }
        else
            a[i]=0;
    }
    int nc=0;
    while(cin>>n)
    {
        memset(visited,0,sizeof(visited));
        nc++;
        b[0]=1;
        cout<<"Case "<         dfs(1);
        cout<     }
    return 0;
}

你可能感兴趣的:(DFS)