HDU 1016 Prime Ring Problem
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 34729 Accepted Submission(s): 15381
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.
![](http://acm.hdu.edu.cn/data/images/1016-1.gif)
Note: the number of first circle should always be 1.
![](http://acm.hdu.edu.cn/data/images/1016-1.gif)
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
Source
Recommend
JGShining
相对简单的一道题,dfs深搜。即在N个数的全排列,找出符合提议的素数组。
注意:一边排列 一边检查
#include<stdio.h> #include<math.h> int num; bool use[20]; int CP[20]; bool isprime(int a) { for(int i=2;i<=sqrt(a+0.0);i++) { if(a%i==0) return false; } return true; } void dfs(int n) { if(n==num&&isprime(1+CP[n-1])) { for(int i=0;i<num;i++) { printf(i==num-1?"%d\n":"%d ",CP[i]); } } else { for(int i=2;i<=num;i++) { if(!use[i]&&isprime(i+CP[n-1])) { CP[n]=i; use[i]=true; dfs(n+1); use[i]=false; } } } } void init() { for(int i=1;i<=num;i++) { use[i]=false; } CP[0]=1; use[1]=true; } int main() { int time=0; while(scanf("%d",&num)!=EOF) { init(); printf("Case %d:\n",++time); dfs(1); puts(""); } }