【动态规划】【数位DP】[SPOJ10606]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

样例输入

2
1 1000
1 9

样例输出

147
4

题目分析

在这里我推荐使用递归版本+记忆化的方法来做本题目方便些
首先我们看到本题目可以使用

f(i,S,k)
来表示一个状态其中i 表示当前已经枚举到了第i 位,k 表示当前是否需要严格小于(0为不需要,1为需要),S为一个3进制的10位数,每一位表示对应的数字出现的奇(1)偶(2)性,同时0表示没有出现过,那么我们对于当前枚举到的数字m 我们可以将其加入,很容易可以发现递推式,其中我们另当前的数范围转换成字符串其中第i 位表示为Ai 该数字一共有n
f(i,j,k)=Ai1p=0f(i+1,g(j,p),0)+f(i+1,g(j,Ai),1)9p=0f(i+1,g(j,p),0)1(k=1)(k1)(i>n)(check(j)==1)
其中check为检查j中的状态是否为奇数位上为2或者0,偶数位上是否为1或0
同时有
g(i,j)={i3ji+3j(i/3j%3==2)(i/3j%3==1||2)
那么我们可以通过递归求得最终的答案就是
cal(R)cal(L1)cal(i)=f(1,0,1)
其中的cal(i) 中的是针对if 那么

代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXS = 19683*3;
const int MAXN = 20;
long long _pow[11]={1,3,9,27,81,243,729,2187,6561,19683}, f[MAXN+2][MAXS+10][2];
int _handle(int s, int u){
    if(!s && !u) return 0;
    if(s/_pow[u]%3 <= 1) s+=_pow[u];
    else s-=_pow[u];
    return s;
}
char s[MAXN+10];
int Len;
long long dp(int u, int S, int k){
    if(~f[u][S][k]) return f[u][S][k];
    f[u][S][k] = 0;
    if(u == 0){
        for(int i=0;i<=9;i++){
            if(i%2==0&&S/_pow[i]%3==2) return f[u][S][k] = 0;
            else if(i%2!=0&&S/_pow[i]%3==1) return f[u][S][k] = 0;
        }
        return f[u][S][k] = 1;
    }
    int up = k != 0 ? s[u]-'0' : 9;
    for(int i=0;i<=up;i++){
        if(k > 0 && i == up) f[u][S][k] += dp(u-1, _handle(S, i), 1);
        else f[u][S][k] += dp(u-1, _handle(S, i), 0);
    }
    return f[u][S][k];
}
long long solve(long long u){
    memset(f, -1, sizeof f);
    Len = 0;
    while(u){s[++Len]=u%10+'0', u/=10;}
    return dp(Len, 0, 1);
}
int main(){
    long long a, b;
    int t;
    scanf("%d", &t);
    while(t--){
        cin>>a>>b;
        cout<<solve(b)-solve(a-1)<<endl;
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章