Transmission Door
Description
A Ring is composed of n (even number) circles as shown in diagram. Put natural numbers 1, 2, ..., n into each circle separately, and the sum of numbers in both adjacent circles should be A prime. Note:the number of first circle should 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 is to write a program, that completes above process.
Sample Input
6 8
Sample Output
1 6 7 4 3 8 5 2
Ideas
Test instructions
Enter a positive integer n, the integer 1,2,3,......,n to form a ring, so that the sum of the adjacent two integers is a prime number. The output sequence header starts at 1, and the same ring should be output exactly once
Exercises
#include <bits/stdc++.h>using namespace Std;const int maxn = 40;bool Is_prime[maxn],vis[maxn];int n,a[maxn];void DFS (int cur) {if (cur = = n && is_prime[a[0] + a[n-1]) //recursive boundary, because it is a loop, so also test the first and last {printf ("%d", a[0]); for (int i = 1;i < n;i++) printf ("%d", A[i]);p rintf ("\ n"); }else{for (int i = 2;i <= n;i++) //try to place each number I {if (!vis[i] && is_prime[i + a[cur-1]) //If I is not used and with the sum of the previous number For prime number {A[cur] = i;vis[i] = true; Set Use flag DFS (CUR+1); vis[i] = false;
UVa 524 Prime Ring Problem (backtracking method)