POJ-2034 Anti-prime Sequences dfs

筛出素数然后直接暴力即可。

代码如下:

#include <cstdlib>
#include <cstring>
#include <cstdio>
#define MAXN 10000
using namespace std;

int N, M, d, p[600005];
int hash[10005], path[10005];

void pre()
{
    int k;
    for (int i = 4; i <= MAXN; i += 2) {
        p[i] = 1;
    }    
    for (int i = 3; i <= 105; i += 2) {
        if (!p[i]) {
            k = 2 * i;     
            for (int j = i * i; j <= MAXN; j += k) {
                p[j] = 1;
            }
        }
    }
}

bool dfs(int x, int step)
{
    path[step] = x;
    if (step >= 2) { 
        int sum = path[step], k = step > d ? d : step;
        for (int i = step-1; i > step-k; --i) {
            sum += path[i];
            if (!p[sum]) {
                return false;
            }
        }
        if (step == M-N+1) {
            for (int i = 1; i <= M-N+1; ++i) {
                printf(i == 1 ? "%d" : ",%d", path[i]);
            }
            puts("");
            return true;
        }
    }
    for (int i = N; i <= M; ++i) {
        if (!hash[i]) {
            hash[i] = 1;
            if (dfs(i, step + 1)) {
                return true;
            }
            hash[i] = 0;
        }
    }
    return false;
}

int main()
{
    int flag;
    pre(); 
    while (scanf("%d %d %d", &N, &M, &d), N|M|d) {
        if (N > M) {
            int t = N; 
            N = M;
            M = t;
        }
        flag = 0;
        memset(hash, 0, sizeof (hash));
        for (int i = N; i <= M; ++i) {
            hash[i] = 1;
            if (dfs(i, 1)) {
                flag = 1;
                break;
            }
            hash[i] = 0;
        }
        if (!flag) {
            puts("No anti-prime sequence exists.");
        }
    }
    return 0;    
}

转载于:https://www.cnblogs.com/Lyush/archive/2012/07/14/2591023.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值