SPOJ10606 BALNUM - Balanced Numbers(数位DP+状压)

Balanced numbers have been used by mathematicians for centuries. A positive integer is considered a balanced number if:

1)      Every even digit appears an odd number of times in its decimal representation

2)      Every odd digit appears an even number of times in its decimal representation

For example, 77, 211, 6222 and 112334445555677 are balanced numbers while 351, 21, and 662 are not.

Given an interval [A, B], your task is to find the amount of balanced numbers in [A, B] where both A and B are included.

Input

The first line contains an integer T representing the number of test cases.

A test case consists of two numbers A and B separated by a single space representing the interval. You may assume that 1 <= A <= B <= 1019 

Output

For each test case, you need to write a number in a single line: the amount of balanced numbers in the corresponding interval

Example

Input:
2
1 1000
1 9
Output:
147
4

题意:求l-r之间13579是偶数个,24680是奇数个的数的个数

题解:状压压一下每一位是奇是偶,1表示奇,2表示偶,0表示没取
dp[pos][sta]表示第pos位之前sta的数有几个
最基础的数位DP写法
记得去一下前导零

代码如下:
#include<bits/stdc++.h>
using namespace std;

int n;
long long l,r;
long long dp[23][60000][2],a[23],b3[12];

int gg(int x,int pos)
{
    return (x%b3[pos+1])/b3[pos];
}

inline int check(int sta)
{
    for(int i=1;i<=9;i+=2)
    {
        if(gg(sta,i)==1) return 0;
    }
    for(int i=0;i<=8;i+=2)
    {
        if(gg(sta,i)==2) return 0;
    }
    return 1;
}

long long dfs(int pos,int sta,int lim,int lim2)
{
    if(pos<=0) return check(sta);
    if(!lim&&dp[pos][sta][lim2]!=-1) return dp[pos][sta][lim2];
    int up=lim?a[pos]:9;
    long long res=0;
    int nextsta;
    for(int i=0;i<=up;i++)
    {
        if(!lim2&&i==0) 
        {
            res+=dfs(pos-1,sta,lim&&i==a[pos],lim2);
        }
        else
        {
            if(gg(sta,i)!=2) nextsta=sta+b3[i];
            else nextsta=sta-b3[i]; 
            res+=dfs(pos-1,nextsta,lim&&i==a[pos],lim2|1);
        }
    }
    if(!lim) dp[pos][sta][lim2]=res;
    return res; 
}

long long get(long long x)
{
    memset(dp,-1,sizeof(dp));
    int cnt=0;
    while(x)
    {
        a[++cnt]=x%10;
        x/=10;
    }
    return dfs(cnt,0,1,0);
}

int main()
{
    b3[0]=1;
    for(int i=1;i<=11;i++) b3[i]=b3[i-1]*3;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%lld%lld",&l,&r);
        printf("%lld\n",get(r)-get(l-1));
    }
}

 



posted @ 2018-09-29 19:21  Styx-ferryman  阅读(234)  评论(0编辑  收藏  举报