hdu 1016 Prime Ring Problem

来源:互联网 发布:域名注册查询 编辑:程序博客网 时间:2024/04/25 07:49

题意是:用1-N中的所有数组成一个环,条件是相邻的两个数的和是素数。

解题思路:用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.


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
 
代码:
#include<iostream>#include<cmath>#include<algorithm>using namespace std;int n,visit[25],next[25],prime[40];int cnt;void dfs(int k){     int i;     visit[k]=1;     next[cnt++]=k;     if(cnt==n+1)     {       if(prime[next[1]+k])       {         for(i=1;i<n;i++) printf("%d ",next[i]);         printf("%d%\n",next[n]);       }     }     else     {       for(i=2;i<=n;i++)       {         if(prime[i+k]&&!visit[i])         {           dfs(i);         }       }     }     cnt--;     visit[k]=0;}          int main(){    int t=0,i,j;    memset(prime,1,sizeof(prime));    for(i=2;i<40;i++)    {      if(prime[i])      {        for(j=i;i*j<40;j++) prime[i*j]=0;      }    }    while(scanf("%d",&n)!=EOF)    {      memset(visit,0,sizeof(visit));      printf("Case %d:%\n",++t);      cnt=1;      dfs(1);      puts ("") ;    }    return 0;}      

 
原创粉丝点击