HDU1016 Prime Ring Problem DFS

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.

HDU1016       Prime Ring Problem    DFS

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


首先看到这个问题,我想了一下暴力枚举出所有符合条件的,但是过不了,超时了,然后我就看了一下别人的,用的是DFS。
因为不熟,我借鉴了一下,换成了我的风格。
#include <bits/stdc++.h>

using namespace std;
int n,a[20],b[40],c[20];
void fn()
{
    memset(b,0,sizeof(b));
    for(int i=2; i<40; i++)
        if(!b[i])
        {
            for(int j=i*2; j<40; j+=i)
                b[j]=1;
        }
}
void dfs(int num)
{
    if(num==n&&b[a[num-1]+a[0]]==0)
    {
        for(int i=0; i<n; i++)
            printf("%d%c",a[i],i==n-1?'\n':' ');
    }
    else
    {
        for(int i=2; i<=n; i++)
        {
            if(c[i]==0)
            {
                if(!b[a[num-1]+i])
                {
                    a[num++]=i;
                    c[i]=1;
                    dfs(num);
                    c[i]=0;
                    num--;
                }
            }
        }
    }
}
int main()
{
    int t=1;
    fn();
    while(cin>>n)
    {
        memset(c,0,sizeof(c));
        printf("Case %d:\n",t++);
        a[0]=1;
        dfs(1);
        printf("\n");
    }
    return 0;
}
HDU1016       Prime Ring Problem    DFSHDU1016       Prime Ring Problem    DFS 乐@. 发布了7 篇原创文章 · 获赞 3 · 访问量 127 私信 关注
上一篇:Java类设计规约


下一篇:301043 Friend iSpace App