例题7-4 UVA524 素数环 Prime Ring Problem

难度:3

先用的生成测试法(都是按照书上的思路来的),就是枚举排列,会超时,然后就用回溯法,走不下去的就不去走了,注意递归边界的写法以及回溯的写法,

#include 

#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;

int n;
int a[20];
int vis[40];
int check[40];

bool isprime(int x) {
    if (x <= 1) return false;
    for (int i = 2; i * i <= x; i++) {
        if (x % i == 0) return false;
    }
    return true;
}

void dfs(int cur) {
    if (cur == n && check[a[0] + a[n - 1]]) {
        for (int i = 0; i < n; i++) {
            cout << a[i] << (i < n - 1 ? " " : "\n");
        }
        return;
    }
    for (int i = 2; i <= n; i++) {
        if (!vis[i] && check[i + a[cur - 1]]) {
            a[cur] = i;
            vis[i] = 1;
            dfs(cur + 1);
            vis[i] = 0;
        }
    }
}

int main() {
    for (int i = 0; i < 40; i++) {
        if (isprime(i)) check[i] = 1;
        else check[i] = 0;
    }
    int cnt = 1;
    a[0] = 1;
    while (cin >> n) {
        if (cnt > 1) cout << endl;
        cout << "Case " << cnt++ << ":" << endl;
        dfs(1);
    }
    return 0;
}

你可能感兴趣的:(加入目录汇总题解)