您的位置:首页 > 其它

hdu 5898 odd-even number (数位dp)

2016-09-24 16:27 357 查看


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

2016 ACM/ICPC Asia Regional Shenyang Online

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

采用和以前数位dp相同的思路,关于数位dp可以看http://blog.csdn.net/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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: