This BLOG introduction (there is a UVa524 prime ring advanced edition), uva524 Prime Number
[B001] Hi, everyone. Today, my blog was opened on the first day. Today I have a blog question. It was originally entitled UVa524 by OJ, A affiliated Middle School of Capital Normal University, the requirements are as follows:
[Difficulty B] Explain ]--------------------------------------------------------------------------------------------
[Question requirement] enter a positive integer n with an integer of 1, 2, 3 ,......, A certain arrangement of n forms a ring, so that any adjacent two numbers and are prime numbers. The output starts from the integer 1 in a counter-clockwise order, and the same ring is exactly output once. There are multiple possible arrangements, and the principle of first output is arranged in the lexicographically small order.
[Input requirement] a positive integer n
[Input example]
6
[Output instance]
21 4 3 2 5 61 6 5 2 3 4
[Other requirements] data range: n <= 16
[Question analysis] what readers think of first is brute-force search, but when n is 12, it is very slow. This question must be traced back (a bit like dfs deep search ).
[Code]
# Include <cstdio> # include <cstring> int A [20], vis [20]; int n; int t = 0; int is_prime (int n) // determine the prime number {for (int I = 2; I * I <= n; I ++) if (n % I = 0) return 0; return 1 ;} void js (int xx) {if (xx = n & is_prime (A [0] + A [n-1]) {t ++ ;} for (int I = 2; I <= n; I ++) // try every number if (vis [I] = 0 & is_prime (I + A [xx-1]) // determine whether the sum is A prime number {A [xx] = I; vis [I] = 1; js (xx + 1); vis [I] = 0; // clear tag} void dfs (int cur) {if (cur = n & is _ Prime (A [0] + A [n-1]) {t ++;} if (cur = n & is_prime (A [0] + A [n-1]) {for (int I = 0; I <n; I ++) {printf ("% d", A [I]); // print the scheme printf ("% s", I = n-1? "\ N": "");} return;} for (int I = 2; I <= n; I ++) // try every number if (vis [I] = 0 & is_prime (I + A [cur-1]) // determine whether the sum is {A [cur] = I; vis [I] = 1; dfs (cur + 1); vis [I] = 0; // clear mark} int main () // call {# ifdef LOCAL # endifint kase = 0; while (scanf ("% d", & n )! = EOF) {memset (vis, 0, sizeof (vis); A [0] = 1; vis [1] = 1; js (1 ); printf ("% d \ n", t); dfs (1);} return 0 ;}
[Note] This code is a little cumbersome with AC. Please give me a lot of advice (I 've never seen the 2 results in the example WA for four times)