BALNUM - 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
第一反应又是每一个数字都添加一维,又变成11维dp,时空是过不去
其实可以发现,每一个数字只有3中状态,未出现、出现奇数次、出现偶数次,这样就可以采用三进制进行状态压缩,就变成二维状态了
设dp[i][j]表示在前面状态是j的情况下,低i位取满足题意的数的个数
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,len,bit[25];
int w[11],nextStatus[11][3];
long long l,r;
long long dp[25][59105];//dp[i][j]表示在前面状态是j的情况下,低i位取满足题意的数的个数
bool isOK(int status) {
for(int i=0;i<=9;++i,status/=3) {
if((i&1)==1&&status%3==1) {
return false;
}
if((i&1)==0&&status%3==2) {
return false;
}
}
return true;
}
long long dfs(int pos,int status,bool limit) {//pos表示当前考虑的位,status表示高位的状态,limit表示当前位是否有限制
if(pos<=0) {
return isOK(status)?1:0;
}
if(!limit&&dp[pos][status]!=-1) {
return dp[pos][status];
}
int mx=limit?bit[pos]:9;
long long res=0;
for(int i=0;i<=mx;++i) {
res+=dfs(pos-1,(status==0&&i==0)?0:status+nextStatus[i][(status/w[i])%3],limit&&i==mx);//不含前导0的情况
}
if(!limit&&dp[pos][status]==-1) {
dp[pos][status]=res;
}
return res;
}
long long getCnt(long long x) {//返回[1,x]中满足题意的数的答案
len=0;
while(x>0) {
bit[++len]=x%10;
x/=10;
}
return dfs(len,0,true);
}
void init() {//初始化每一位的权值和状态改变量
w[0]=1;
nextStatus[0][0]=1;
nextStatus[0][1]=1;
nextStatus[0][2]=-1;
for(int i=1;i<=9;++i) {
w[i]=w[i-1]*3;
nextStatus[i][0]=nextStatus[i-1][0]*3;
nextStatus[i][1]=nextStatus[i-1][1]*3;
nextStatus[i][2]=nextStatus[i-1][2]*3;
}
memset(dp,-1,sizeof(dp));
}
int main() {
int T;
init();
scanf("%d",&T);
while(T-->0) {
scanf("%lld%lld",&l,&r);
printf("%lld\n",getCnt(r)-getCnt(l-1));
}
return 0;
}