hdu 5898 odd-even number (数位dp)

本文介绍了一道关于寻找特定范围内奇偶数位交替出现的数字数量的问题,并通过数位DP的方法给出了详细的解答过程及代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

odd-even number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 661    Accepted Submission(s): 362


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


解题思路:因为要求奇数连续出现偶数次,偶数连续出现奇数次,均是跟数位有关的操作,考虑使用数位dp思路。

采用和以前数位dp相同的思路,关于数位dp可以看http://blog.youkuaiyun.com/wchhlbt/article/details/52119930

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 20;
ll n;
ll dp[maxn][20][2], bit[maxn];


ll dfs(int pos,int pre,int limit,int ok)//pos数字位数,pre
{
    if(pos < 1 && ok) return 1;//如果顺利搜索到了第零位,说明这个数满足条件,返回1
    if(pos < 1 && !ok) return 0;
    if(!limit && dp[pos][pre][ok] != -1) return dp[pos][pre][ok];//记忆化搜索的关键
    ll ret = 0;
    int len = limit?bit[pos]:9;//如果处于非上界状态下,数字可以枚举0-9,处于上界状态则需要考虑给出的上界在该位的数字
    for(int i = 0; i <= len; i++)
    {
        if(pre==11) {
            if(i==0)
                ret += dfs(pos-1,  11, limit&&i==len, 1);
            else
                ret += dfs(pos-1, i, limit&&i==len, (i+1)%2);
            continue;
        }
        if(pre%2 != i%2)
        {
            if(ok==0)
                continue;
            else
            {
                ret += dfs(pos-1,  i, limit&&i==len, (i+1)%2);
            }
        }
        else
        {
            ret += dfs(pos-1,  i, limit&&i==len, !ok);
        }
        //ret += dfs(pos-1,  i, limit&&i==len);
    }
    if(!limit) dp[pos][pre][ok] = ret;
    return ret;
}


ll solve(ll n)//预处理函数,将所给定的数字,处理为每个位置上的数字(上界)
{
    int len = 0;
    while(n)
    {
        bit[++len] = n%10;
        n /= 10;
    }
    return dfs(len, 11, 1, 1);
}


int main()
{
    int t;
    ll a,b;
    cin>>t;
    memset(dp, -1, sizeof(dp));
    for(int i = 1; i<= t ; i++)
    {
        cin>>a>>b;
        //cout << solve(b) << ' ' << solve(a-1) << endl;
        printf("Case #%d: %I64d\n",i,solve(b)-solve(a-1));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值