码迷,mamicode.com
首页 > 其他好文 > 详细

SCUT - 289 - 小O的数字 - 数位dp

时间:2019-06-16 00:25:13      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:amp   not   tps   printf   eof   uri   dfs   open   mit   

https://scut.online/p/289
一个水到飞起的模板数位dp。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

bool notp[2000];

const int MAXS1=200;
const int MAXS2=2000;

int a[20];
ll dp[20][MAXS1][MAXS2];
ll dfs(int pos,int s1,int s2,bool lead,bool limit) {
    if(pos==-1) {
        if(notp[s1]||notp[s2])
            return 0;
        else
            return 1;
    }
    if(!limit && !lead && dp[pos][s1][s2]!=-1)
        return dp[pos][s1][s2];
    int up=limit?a[pos]:9;
    ll ans=0;
    for(int i=0; i<=up; i++) {
        ans+=dfs(pos-1,s1+i,s2+i*i,lead && i==0,limit && i==a[pos]);
    }
    if(!limit && !lead)
        dp[pos][s1][s2]=ans;
    return ans;
}

ll solve(ll x) {
    if(x<=0)
        return 0;

    int pos=0;
    while(x) {
        a[pos++]=x%10;
        x/=10;
    }

    return dfs(pos-1,0,0,true,true);
}

int main() {
#ifdef Yinku
    freopen("Yinku.in","r",stdin);
#endif // Yinku
    memset(dp,-1,sizeof(dp));
    notp[0]=1;
    notp[1]=1;
    for(int i=2; i<2000; i++) {
        if(!notp[i]) {
            for(int j=i+i; j<2000; j+=i) {
                notp[j]=1;
            }
        }
    }

    int T;
    scanf("%d",&T);
    ll le,ri;
    while(T--) {
        scanf("%lld%lld",&le,&ri);
        printf("%lld\n",solve(ri)-solve(le-1));
    }
}

SCUT - 289 - 小O的数字 - 数位dp

标签:amp   not   tps   printf   eof   uri   dfs   open   mit   

原文地址:https://www.cnblogs.com/Yinku/p/11029378.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!