杭电1016————素数环之DFS

来源:互联网 发布:淘宝优惠券领券链接 编辑:程序博客网 时间:2024/05/28 01:36

Prime Ring Problem

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


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题目,代码经过测试AC,但是时间用了大约500MS,亲测当n>=11时,这段代码卡顿。杭电的范围是0<n<20,目测是数据水了。杭电最快是15MS。
#include <stdio.h>#include <string.h>#include <math.h>#define maxn 30int prime[maxn],vis[maxn];/*prime记录要输出的序列 vis表示当前数字是否已被使用*/ int n;/*the number*/void print(){for(int i = 0;i < n;i++){if(i != n-1)printf("%d ",prime[i]);elseprintf("%d\n",prime[i]);}}int isprime(int x){int flag = 1;for(int i = 2;i <= sqrt(x);i++){if(x % i == 0){flag = 0;break;}}return flag;}void DFS(int x,int count)/*x记录数字的值,count记录第几个数*/ {if( isprime(x+1) && count == n)/*终止条件,即递归出口*/ {print();return ;}else{for(int i = 2 ; i <= n; i++){if( isprime(i+x) && vis[i] == 0){vis[i] = 1;prime[count++] = i;DFS(i,count);count--;vis[i] = 0;}}}}int main(){int cases = 0;/*case x*/while(scanf("%d",&n) != EOF){cases++;memset(prime,0,sizeof(prime));memset(vis,0,sizeof(vis));prime[0] = 1;/*the begining number is always one*/vis[1] = 1;/*one has been used*/ printf("Case %d:\n",cases);DFS(1,1);printf("\n");} return 0;}
0 0
原创粉丝点击