SPOJ - BALNUM Balanced Numbers(数位dp+三进制状压)

Balanced Numbers

 

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




题意:奇数个数为偶数,偶数个数为奇数。

用三进制来表示0-9的状态,0为没有,1为奇数个,2为偶数个。
3^10约为60000。
注意判断前导零。


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

ll a[20],p[12],st[60000][12];
ll dp[20][60000];

ll dfs(int pos,int sta,bool lead,bool limit){
    
    if(pos==-1){
        for(int i=1;i<=9;i+=2){
            if(st[sta][i]==1) return 0;
        }
        for(int i=0;i<=9;i+=2){
            if(st[sta][i]==2) return 0;
        }
        return 1;
    }
    if(!lead&&!limit&&dp[pos][sta]>-1) return dp[pos][sta];
    int up=limit?a[pos]:9;
    ll cnt=0;
    for(int i=0;i<=up;i++){
        if(i==0&&lead){
            cnt+=dfs(pos-1,sta,lead&&i==0,limit&&i==a[pos]);
        }
        else if(st[sta][i]==2){
            cnt+=dfs(pos-1,sta-p[i],lead&&i==0,limit&&i==a[pos]);
        }
        else{
            cnt+=dfs(pos-1,sta+p[i],lead&&i==0,limit&&i==a[pos]);
        }
    }
    if(!lead&&!limit) dp[pos][sta]=cnt;
    return cnt;
}
ll solve(ll x){
    int pos=0;
    while(x){
        a[pos++]=x%10;
        x/=10;
    }
    return dfs(pos-1,0,true,true);
}
int main()
{
    int t;
    ll l,r;
    scanf("%d",&t);
    memset(dp,-1,sizeof(dp));
    p[0]=1;
    for(int i=1;i<=10;i++){
        p[i]=p[i-1]*3;
    }
    for(int i=1;i<p[10];i++){
        int ii=i,c=-1;
        while(ii){
            c++;
            st[i][c]=ii%3;
            ii/=3;
        }
    }
    while(t--){
        scanf("%lld%lld",&l,&r);
        printf("%lld\n",(solve(r)-solve(l-1)));
    }
    return 0;
}

 

posted @ 2019-01-28 03:00  yzm10  阅读(156)  评论(0编辑  收藏  举报