HDU-1016-Prime Ring Problem DFS

来源:互联网 发布:淘宝蓝海龙腾黑不黑 编辑:程序博客网 时间:2024/06/05 18:16

Prime Ring Problem

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


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
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
 
思路:
简单的DFS,做过突然想温习一下,旧题新写

代码:
#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<cmath>#include<string>using namespace std;const int MAXN=21;bool flag[MAXN];int ans[MAXN];int total=0;int t=1;int N;bool check(int x, int y){    x+=y;    int i=2;    while(i<=sqrt(x)&&x%i)    {        i++;    }    if(i>sqrt(x))        return true;    return false;}void print(){    printf("%d",ans[1]);    for(int i=2;i<=N;i++)    {        printf(" %d",ans[i]);    }    printf("\n");}void dfs(int num){    for(int i=2;i<=N;i++)    {        if(check(ans[num-1],i)&&!flag[i])        {            ans[num]=i;            flag[i]=true;            if(num==N)            {                if(check(ans[num],ans[1]))                    print();            }            else            {                dfs(num+1);            }            flag[i]=false;        }    }}int main(){    while(scanf("%d",&N)!=EOF)    {        memset(flag,false,sizeof(flag));        printf("Case %d:\n",t);        ans[1]=1;        dfs(2);        printf("\n");        t++;    }    return 0;}


0 0