题目描述
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
1 | 6 |
Sample Output
1 | Case 1: |
思路分析
这题对我来说有些难,最主要是这个递归的过程有点难懂。还是要多看看代码才行,贴出来的代码还是能懂的,但是自己写却比较困难了。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
int ans[22];
int visit[22];
int n;
int prime[] = {2,3,5,7,11,13,17,19,23,29,31,37,41};
bool judgePrime(int x){
for(int i=0; i<13; i++){
if(prime[i] == x) return true;
}
return false;
}
void DFS(int x){
if(x == n){
if(judgePrime(1+ans[n])){
for(int i=1; i<=n; i++){
if(i != 1) printf(" ");
printf("%d", ans[i]);
}
printf("\n");
}
return;
}
else{
for(int i=2; i<=n; i++){
if(!visit[i] && judgePrime(i + ans[x])){
visit[i] = 1;
ans[x+1] = i;
DFS(x+1);
visit[i] = 0; // 这里需要重置为0,以便于下次递归入口使用。
}
}
}
}
int main(){
int cas = 0;
while(scanf("%d", &n) !=EOF){
cas++;
for(int i=0; i<22; i++) visit[i] = 0;
ans[1] = 1;
printf("Case %d:\n", cas);
visit[1] = true;
DFS(1);
printf("\n");
}
}