University of Virginia
Ultraviolet-524 Prime Ring Problem
Time Limit:3000 MS
Memory Limit:0 KB
64bit IO Format:% Lld & % llu
Description
A ring is composed of n (even number) circles as shown in digoal. Put natural numbers into each circle separately, and the sum of numbers in two adjacent circles shocould be a prime.
Note:The number of first circle shoshould always be 1.
Input
N (0 <n <= 16)
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.
You are to write a program that completes abve process.
Sample Input
68
Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
Original question on page 1 of zishu
Question: enter a positive integer n to form a ring consisting of 1-n. the adjacent two integers are prime numbers. The output starts from integer 1 and is arranged in a counter-clockwise manner. The same ring is output exactly once,N (0 <n <= 16)
Brute-force solution will time out, apply backtracking, and perform in-depth search first
# Include <iostream> # include <cstring> # include <cmath> using namespace std; int n; int a [20], vis [20]; int isp (int n) // determine whether it is a prime number {if (n <2) return false; for (int I = 2; I * I <= n; I ++) {if (n % I = 0) return false;} return true;} void dfs (int s) {if (s = n & isp (a [1] + a [n]) // recursive boundary. Do not forget to test the first and last numbers {for (int I = 1; I <n; I ++) cout <a [I] <""; cout <a [n] <endl;} else {for (int I = 2; I <= n; I ++) {if (! Vis [I] & isp (I + a [s]) // If I has not been used, and the sum of values with money is a prime number {a [s + 1] = I; vis [I] = 1; // mark dfs (s + 1 ); vis [I] = 0; // clear mark }}} int main () {int t = 0; while (cin> n) {memset (vis, 0, sizeof (vis); a [1] = 1; if (t! = 0) cout <endl; // note the output format t ++. cout <"Case" <t <":" <endl; dfs (1);} return 0 ;}