UVA524 Prime Ring Problem(DFS + 回溯)

本题vjudge链接

  • 题意:给你一个数n,让你求出所有素数环,素数环:利用 1 ~ n来排列组合成的一个环,相邻的两个数的和必须都是素数
  • 直接dfs遍历所有排列,途中要剪枝,如果当前放的数和前面的数的和不是素数就直接剪了
  • 画出解答树更好懂
  • 代码如下
#include <cstdio>
#include <cstring>

using namespace std;

int kase = 0, n, arr[30];
bool isp[] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0,
 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0,
 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0,
  1, 0, 0, 0, 1, 0, 0};
bool vis[30];

void dfs(int cur, int *A) {
    if (cur == n - 1) {
        if (!isp[1 + A[n - 1]]) return;
        bool f = true;
        for (int i = 0; i < n; i++) {
            if (f) f = !f;
            else printf(" ");
            printf("%d", A[i]);
        }
        puts("");
        return;
    }
    for (int i = 2; i <= n; i++) {
        if (vis[i]) continue;
        if (isp[A[cur] + i]) {
            A[cur + 1] = i;
            vis[i] = true;
            dfs(cur + 1, A);
            vis[i] = false;
        }
    }
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#endif
    arr[0] = 1;
    bool f = true;
    while (~scanf("%d", &n)) {
        if (f) f = !f;
        else puts("");
        printf("Case %d:\n", ++kase);
        dfs(0, arr);
        memset(vis, 0, sizeof vis);
    }
    return 0;
}

原地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值