HDU5898 odd-even number (数位DP)shenyang网赛



odd-even number
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 460    Accepted Submission(s): 247


Problem Description

For a number,if the length of continuous odd digits is even and the length of continuous even digits is odd,we call it odd-even number.Now we want to know the amount of odd-even number between L,R(1<=L<=R<= 9*10^18).

 


Input

First line a t,then t cases.every line contains two integers L and R.

 


Output

Print the output for each case on one line in the format as shown below.

 


Sample Input

2   
1 100   
110 220


 


Sample Output

Case #1: 29
Case #2: 36


 


Source

 2016 ACM/ICPC Asia Regional Shenyang Online

题意:

问区间中 满足某种特征的数的个数(特征:连续奇数的个数为偶数 连续偶数的个数为奇数)

题解:数位DP的题往往一看就能看出来,还是设计状态 dp[I][j][k]当前位置,前一位为奇还是偶 是否需要一个数来使它满足题意. 则申请dp[20][2][2]就可以,空间绝对没问题。设计状态转移 --->看代码

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include <stack>
#include <map>
#define ll long long
using namespace std;
int a[20];
ll dp[20][2][2];
ll dfs(int pos,int sta ,int need,bool limit,bool lead)//位置,前面为奇还是偶,是否需要一个数,是否有限制,是否有前导0
{
    if(pos==-1)
        return need==1?0:1;//有需要说明不满足
    if(!limit&&dp[pos][sta][need]!=-1&&!lead)
        return dp[pos][sta][need];
    ll ans=0;
    int up=limit?a[pos]:9;
    for(int i=0;i<=up;i++)
    {
        if(lead)//如果有前导0
        {
            if(i==0)//还是有前导0
                ans+=dfs(pos-1,0,0,limit&&i==a[pos],true);
            else//没有前导0了
                ans+=dfs(pos-1,i%2,i%2,limit&&i==a[pos],false);

        }
        else if(i%2==1)
        {
            if(sta%2==1)//如果前一个数为奇数,这个数也为奇数,则当前需要一个数,现在就不需要了,所以need取反
                ans+=dfs(pos-1,1,!need,limit&&i==a[pos],false);
            else
            {
                if(need==0)//前一个是为偶数,没有需要的时候才能继续dfs
                    ans+=dfs(pos-1,1,1,limit&&i==a[pos],false);
            }

        }
        else//同理
        {
             if(sta%2==0)
                ans+=dfs(pos-1,0,!need,limit&&i==a[pos],false);
            else
            {
                if(need==0)
                    ans+=dfs(pos-1,0,0,limit&&i==a[pos],false);
            }

        }
    }
    if(!limit&&!lead)
        dp[pos][sta][need]=ans;
    return ans;
}
ll solo(ll x)
{
    int pos=0;
    while(x)
    {
        a[pos++]=x%10;
        x/=10;
    }
    return dfs(pos-1,0,0,true,true);
}
int main()
{
    int t;
    ll l,r;
    memset(dp,-1,sizeof(dp));
    scanf("%d",&t);
    for(int i=1;i<=t;i++)
    {
        scanf("%I64d%I64d",&l,&r);
        printf("Case #%d: %I64d\n",i,solo(r)-solo(l-1));
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值