hdu1016Prime Ring Problem解题报告---素数环(搜索入门题)

版权声明:转载请注明出处:https://blog.csdn.net/qq1013459920 https://blog.csdn.net/qq1013459920/article/details/84671609

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 68491    Accepted Submission(s): 29324


 

Problem 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

以前觉得很难的一道题(其实就是一道水题...)这个素数环起点是1,一开始把以1到n为起点的所有情况都搜索了,仔细看题发现只要从1开始的情况

AC Code:

#include <iostream>
#include<cstdint>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
static const int MAX_N = 1e6 + 5;
typedef long long ll;
int n;
int vv[25];
bool vis[25];
bool is_prime(int x){
    if(x == 1) return false;
    if(x == 2) return true;
    if(x % 2 == 0) return false;
    for(int i = 3; i * i <= x; i += 2){
        if(x % i == 0) return false;
    }
    return true;
}

void dfs(int s, int len){
    if(len == n && is_prime(vv[len] + vv[1])){
        for(int i = 1; i < len; i++){
            printf("%d ", vv[i]);
        }
        printf("%d\n", vv[len]);
        return;
    }
    if(len > n) return;
    for(int i = 1; i <= n; i++){
        if(vis[i]) continue;
        if(is_prime(s + i)) {
            vv[len + 1] = i;
            vis[i] = true;
            dfs(i, len + 1);
            vis[i] = false;
        }
    }
}
int main(){
    int cas = 1;
    while(scanf("%d", &n) != EOF){
        memset(vis, false, sizeof(vis));
        printf("Case %d:\n", cas++);
        vis[1] = true;
        vv[1] = 1;
        dfs(1, 1);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq1013459920/article/details/84671609