SPOJ BANLUM 数位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


题意:要判断一个数字中 0~9各个数出现的奇偶性,偶数(如 2)出现奇数次,奇数出现偶数次。如果某个偶数出现次数为0次也视作合法。
求[l,r]区间中合法数字的数量。
做了几道二进制状态压缩的题后就遇到了三进制压缩,emmmm。。。
使用三进制来压缩,0表示没出现,1表示出现奇数次,2表示出现偶数次 状态转换为 0 -> 1 -> 2 -> 1 -> 2

#include<cstdio>
#include<cstring>
#define ll long long

int digit[20];
ll dp[20][59100];

int check(int s){
    int flag = 1;
    while(s){
        if((s%3)==0);
        else if((s%3)%2==flag);
        else return false;
        flag ^= 1;
        s /= 3;
    }
    return true;
}
int getnew(int s,int x){
    int t = 1;
    for(int i=0;i<x;i++)t*=3;
    switch((s/t)%3){
        case 0:
            s+=t;
            break;
        case 1:
            s+=t;
            break;
        case 2:
            s-=t;
            break;
    }
    return s;
}
ll dfs(int d,int s,int one,bool shangxian){
    if(d == 0)return check(s);
    if(!shangxian && dp[d][s]!=-1)
        return dp[d][s];
    int maxn = shangxian?digit[d]:9;
    ll cnt = 0;
    for(int i=0;i<=maxn;i++){
        cnt += dfs(d-1,(one||i)?(getnew(s,i)):0,one||i,shangxian&&i==maxn);
    }
    return shangxian?cnt:dp[d][s]=cnt;
}
ll solve(ll x){
    int k = 0;
    while(x){
        digit[++k] = x % 10;
        x /= 10;
    }
    return dfs(k,0,0,1);
}
int main(){
    int t;
    ll l, r;
    memset(dp,-1,sizeof(dp));
    scanf("%d",&t);
    while(t--){
        scanf("%lld%lld",&l,&r);
        printf("%lld\n",solve(r)-solve(l-1));
    }
    return 0;
}
View Code

 




posted @ 2019-05-16 22:09  kongbb  阅读(155)  评论(0编辑  收藏  举报