Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
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代码:
#include<iostream> #include<cstring> #define MAX 30 using namespace std; int ring[MAX], vis[MAX], num, cnt = 1; const int pri[11] = {3,5,7,11,13,17,19,23,29,31,37}; void dfs(int cur) { if (cur == num - 1) { // cout << cur << ' ' << ring[num - 1] + 1 << endl; int ok = 0; for (int i = 0; i < 11; i++) if (ring[num -1] + 1 == pri[i]) ok = 1; if (ok == 0) return; for (int i = 0; i < num - 1; i++) cout << ring[i] << ' '; cout << ring[num - 1] << endl; return; } vis[ring[cur]] = 1; for (int i = 0; i < 11; i++) { if (vis[pri[i] - ring[cur]] == 0 && pri[i] - ring[cur] > 1) { if (pri[i] - ring[cur] > num) break; ring[cur + 1] = pri[i] - ring[cur]; dfs(cur + 1); } } vis[ring[cur]] = 0; } int main() { while(cin >> num) { memset(ring, 0, sizeof (ring)); memset(vis, 0, sizeof (vis)); ring[0] = 1; cout << "Case " << cnt << ':' << endl; cnt++; dfs(0); cout << endl; } }