HDU-5898 odd-even number (数位DP)

题意

对于一个数 a ,如果 a 的所有连续偶数长度均为奇数且所有连续奇数长度均为偶数,则称 a o d d e v e n n u m b e r 。给定一个区间 [ L , R ] ,求区间 [ L , R ] o d d e v e n n u m b e r 的个数。
1 L R 9 × 10 18

思路

数位DP的套路已经大体上摸清了,需要什么就额外存什么。比如这道题,只用额外存 f 1 , f 2 两个值,分别表示连续奇数长度和连续偶数长度,其中一者不为零时另一者为零,初始 f 1 , f 2 均为 0 表示前导零。

代码

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define FOR(i,x,y) for(int i=(x);i<=(y);i++)
#define DOR(i,x,y) for(int i=(x);i>=(y);i--)
typedef long long LL;
using namespace std;
LL dp[20][20][20];
int num[20];

LL dfs(int k,int f1,int f2,bool ismax)
{
    if(k==0)return (!f1||!(f1&1))&&(!f2||(f2&1));
    if(!ismax && ~dp[k][f1][f2])return dp[k][f1][f2];
    int maxer=ismax?num[k]:9;
    LL res=0;
    FOR(i,0,maxer)
    {
        if(!(f1|f2|i))res+=dfs(k-1,f1,f2,ismax&&i==maxer);
        else if((i&1) && ((f1||f2&1) || !(f1|f2)))res+=dfs(k-1,f1+1,0,ismax&&i==maxer);
        else if(!(i&1) && ((f2||!(f1&1)) || !(f1|f2)))res+=dfs(k-1,0,f2+1,ismax&&i==maxer);
    }
    if(!ismax)dp[k][f1][f2]=res;
    return res;
}
LL solve(LL x)
{
    int p=0;
    while(x)
    {
        num[++p]=x%10;
        x/=10;
    }
    return dfs(p,0,0,1);
}

int main()
{
    int T;
    scanf("%d",&T);
    memset(dp,-1,sizeof(dp));
    FOR(Ti,1,T)
    {
        LL L,R;
        scanf("%lld%lld",&L,&R);
        printf("Case #%d: %lld\n",Ti,solve(R)-solve(L-1));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/paulliant/article/details/80466712