【预处理 && 记忆化搜索】URAL - 1586 Threeprime Numbers

Step1 Problem:

求长度为n,任取连续的三位组成的数都是素数的个数。
数据范围
3 <= n <= 10000.

Step2 Involving algorithms:

dp记忆化搜索

Step3 Ideas:

预处理出 100-1000的所有素数
dfs的时候,参数:第几位,上两位,上一位。
继续搜索的条件满足连续三位组成的数都是素数

Step4 Code:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int MOD = 1e9+9;
bool q[1000];
ll dp[10005][15][15];
int n;
ll dfs(int pos, int pre, int pre1)
{
    if(pos < 0) return 1;
    if(dp[pos][pre][pre1] != -1) return dp[pos][pre][pre1];
    int i;
    if(pos == n-1) i = 1;
    else i = 0;
    ll res = 0;
    for(; i <= 9; i++)
    {
        if(pre != -1 && pre1 != -1)
        {
            if(q[pre*100+pre1*10+i]) {
            res += dfs(pos-1, pre1, i);
            res %= MOD;
            }
        }
        else res += dfs(pos-1, pre1, i); res %= MOD;

    }
    return dp[pos][pre][pre1] = res;
}
int main()
{
    memset(q, 0, sizeof(q));
    for(int i = 100; i < 1000; i++)
    {
        int j;
        for(j = 2; j < i; j++)
        {
            if(i%j == 0) break;
        }
        if(j == i) {
            q[i] = 1;
        }
    }
    memset(dp, -1, sizeof(dp));
    while(cin >> n)
    {
        cout << dfs(n-1, -1, -1) << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值