HDU 1016 Prime Ring Problem

Posted titordong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 1016 Prime Ring Problem相关的知识,希望对你有一定的参考价值。

题目链接:HDU 1016

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.

技术分享图片

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.

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个点,这n个点由1-n这n个数组成,其中第一个点固定是1,且保证任意相连的两个数之和是素数,在输入n以后把所有符合条件的数字排列输出。

题解:

虽然是n<20,其实数据还是很大的,用DFS去跑,符合条件就输出,在本地运行时,发现当n为奇数时无解,就加上了奇偶判断,节省了一定的时间。另外在初始化时打一个素数表,注意下细节这就是道简单题。

代码

#include<string>
#include<cstring>
using namespace std;
int n;
int state[22] = { 0 };
bool prime[110] = { 0 };
void Init() {
    for (int i(2); i < 45; i++)
        for (int j(2); i*j <= 45; j++)
            prime[i*j] = 1;
}
int a[22] = { 1,1 };
int ans;
void dfs(int x) {
    if (x == n+1) {
        if (!prime[a[n]+ a[1]]) {
            ans++;
            for (int i(1); i <= n; i++) {
                if (i > 1)
                    cout << ‘ ‘;
                cout << a[i];
            }
            cout << endl;
            return;
        }
        else return;
    }
    for (int i(2); i <= n; i++) {
        if (!state[i]&&!prime[i + a[x - 1]]) {
            a[x] = i;
            state[i] = 1;
            dfs(x + 1);
            state[i]=0;
        }
    }
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    Init();
    int Case = 1;
    while (cin >> n,n) {
        ans = 0;
        memset(state, 0, sizeof state);
        cout << "Case " << Case++ << ":" << endl;
        dfs(2);
        cout <<ans<< endl;
    }
}







以上是关于HDU 1016 Prime Ring Problem的主要内容,如果未能解决你的问题,请参考以下文章

hdu1016 Prime Ring Problem

HDU 1016 Prime Ring Problem(DFS)

HDU-1016-Prime Ring Problem

Prime Ring Problem HDU - 1016 (dfs)

Prime Ring Problem HDU - 1016

HDU 1016 Prime Ring Problem