【动态规划】【数位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
题目分析
在这里我推荐使用递归版本+记忆化的方法来做本题目方便些
首先我们看到本题目可以使用
同时有
代码
#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;
}