524 - Prime Ring Problem

来源:互联网 发布:qq飞车8周年剃刀数据 编辑:程序博客网 时间:2024/06/10 17:29

Prime Ring Problem

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers1,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<n16)

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 above process.

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

输入正整数n,把整数1, 2, 3,…, n组成一个环,使得相邻两个整数之和均为素数。输出时从整数1开始逆时针排列。同一个环应恰好输出一次。n≤16。

样例输入:

6

样例输出:

1 4 3 2 5 6
1 6 5 2 3 4

//#define LOCAL#include <iostream>#include <cmath>#include <cstring>#include <cstdio>using namespace std;const int maxNum = 1005;// 素数表// 0:为素数// 1:为合数int isp[maxNum];// 生成从1到2n的素数表void isPrime(int n) {    isp[0] = 1;    isp[1] = 1;    // 埃拉托斯特尼筛法    for(int i = 2; i < sqrt(2 * n); i++) {        for(int j = i * 2; j <= 2 * n; j += i) {            isp[j] = 1;        }    }}// 序列个数int n;// 序列数组int A[20];// 访问数组int vis[20];// 深搜和回朔法void dfs(int cur) {    // 递归边界    // 第一个和最后一个相加是否为素数    if(cur == n && !isp[A[0] + A[cur - 1]]) {        cout << A[0];        for(int i = 1; i < n; i++) {            cout << " " << A[i];        }        cout << endl;    } else {        for(int i = 2; i <= n; i++) {            // i并未使用过且cur和cur - 1之和是素数            if(!vis[i] && !isp[A[cur - 1] + i]) {                A[cur] = i;                // 回溯法                vis[i] = 1;                dfs(cur + 1);                vis[i] = 0;            }        }    }}int main() {    #ifdef LOCAL        freopen("data.524.in", "r", stdin);        freopen("data.524.out", "w", stdout);    #endif // LOCAL    int kase = 0;    while(cin >> n) {        if(kase > 0) {            cout << endl;        }        cout << "Case " << ++kase << ":" << endl;        memset(isp, 0, sizeof(isp));        memset(vis, 0, sizeof(vis));        // 生成从1到2n的素数表        isPrime(n);        A[0] = 1;        dfs(1);    }    return 0;}
0 0
原创粉丝点击