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

FZU2109:Mountain Number(数位DP)

时间:2014-12-10 16:18:23      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:fzu   dp   

bubuko.com,布布扣 Problem Description

One integer number x is called "Mountain Number" if:

(1) x>0 and x is an integer;

(2) Assume x=a[0]a[1]...a[len-2]a[len-1](0≤a[i]≤9, a[0] is positive). Any a[2i+1] is larger or equal to a[2i] and a[2i+2](if exists).

For example, 111, 132, 893, 7 are "Mountain Number" while 123, 10, 76889 are not "Mountain Number".

Now you are given L and R, how many "Mountain Number" can be found between L and R (inclusive) ?

bubuko.com,布布扣 Input

The first line of the input contains an integer T (T≤100), indicating the number of test cases.

Then T cases, for any case, only two integers L and R (1≤L≤R≤1,000,000,000).

bubuko.com,布布扣 Output

For each test case, output the number of "Mountain Number" between L and R in a single line.

bubuko.com,布布扣 Sample Input

31 101 1001 1000

bubuko.com,布布扣 Sample Output

954384
要求出区间内偶数为大于奇数位的数字的个数
dp[i][j][k] 表示在第i个位置时,前面是j,现在这位是奇数位还是偶数位的数目


#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

int t;
int bit[20],len,l,r;
int dp[20][10][2];

int dfs(int pos,int pre,int odd,int zero,int doing)//pos-当前位置,pre前一个数字,odd,现在位置的奇偶性,zero是否还是前导0,doing是否美剧导了边界
{
    if(pos==-1) return 1;
    if(dp[pos][pre][odd]!=-1 && !doing)
        return dp[pos][pre][odd];
    int end = doing?bit[pos]:9;
    int ans = 0;
    for(int i = 0; i<=end; i++)
    {
        if(!(i||zero))
            ans+=dfs(pos-1,9,0,zero||i,doing&&i==end);
        else if(odd && pre<=i)
            ans+=dfs(pos-1,i,!odd,zero||i,doing&&i==end);
        else if(!odd && pre>=i)
            ans+=dfs(pos-1,i,!odd,zero||i,doing&&i==end);
    }
    if(!doing)
        dp[pos][pre][odd] = ans;
    return ans;
}

int cal(int x)
{
    len = 0;
    while(x)
    {
        bit[len++] = x%10;
        x/=10;
    }
    return dfs(len-1,9,0,0,1);//刚刚开始在前面加个9,方便后面判断
}

int main()
{
    scanf("%d",&t);
    while(t--)
    {
        memset(dp,-1,sizeof(dp));
        scanf("%d%d",&l,&r);
        printf("%d\n",cal(r)-cal(l-1));
    }

    return 0;
}


FZU2109:Mountain Number(数位DP)

标签:fzu   dp   

原文地址:http://blog.csdn.net/libin56842/article/details/41847295

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