杭电1016————素数环之DFS
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.
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.
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题目,代码经过测试AC,但是时间用了大约500MS,亲测当n>=11时,这段代码卡顿。杭电的范围是0<n<20,目测是数据水了。杭电最快是15MS。#include <stdio.h> #include <string.h> #include <math.h> #define maxn 30 int 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]); else printf("%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; }