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
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 |
Codes ![]() 1 #include <stdio.h> 2 #include <string.h> 3 #define N 20 4 int primeMap[N + N]; //record which num is prime 5 int isUsed[N + 5]; //judge if the num is used 6 int store[N + 5]; //record the path 7 int n, count = 1; 8 void Initializing() // 0 means prime, 1 means not prime 9 { 10 int i, j; 11 for (i = 4; i < 40; i++) 12 { 13 for (j = 2; j <= i / 2; j++) 14 { 15 if (i % j == 0) 16 { 17 primeMap[i] = 1; 18 break; 19 } 20 } 21 } 22 } 23 void DFS(int step) 24 { 25 int i; 26 //the exit condition 27 if (step == n && primeMap[store[step] + 1] == 0) 28 { 29 for(i = 1; i < n; i++) 30 printf("%d ",store[i]); 31 printf("%d\n", store[n]); 32 } 33 //find the available num 34 for (i = 2; i <= n; i++) 35 { 36 //is not prime or the num is used 37 if (primeMap[store[step] + i] == 1 || isUsed[i] == 1) 38 continue; 39 //recursion 40 isUsed[i] = 1; 41 store[step + 1] = i; 42 DFS(step + 1); 43 isUsed[i] = 0; 44 } 45 } 46 int main() 47 { 48 Initializing(); 49 while (scanf("%d",&n) != EOF) 50 { 51 memset(isUsed,0,sizeof(isUsed)); 52 store[1] = 1; 53 printf("Case %d:\n", count++); 54 //remove the odd, because it's useless 55 if (n % 2 == 0) 56 DFS(1); 57 puts(""); 58 } 59 return 0; 60 }
|
Recommend
JGShining
|