Balanced numbers have been used by mathematicians for centuries. A positive integer is considered a balanced number if:
-
Every even digit appears an odd number of times in its decimal representation
-
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
题意:对于一个数字,要求它的数位上的每一个偶数都出现了奇数次,每一个奇数都出现了偶数次。求l-r范围内有多少满足条件的数字。
思路:三进制压缩状态,第i位为0,1,2分别表示前面状态中,数字i,出现0次,奇数次,和偶数次,0-9有十个数那么需要十位的三进制数,也就是3^9这么大的数字。
所以dp[i][j]表示,从高到低枚举到第i位,并且前面的数字出现过的状态是j的情况下有多少满足条件的数字。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#define ll long long
using namespace std;
ll dp[20][60000];
int num[20];
bool check(int state)
{
int num2[15];
for(int i=0;i<10;i++)
{
num2[i]=state%3;
state/=3;
}
for(int i=0;i<10;i++)
{
if(i%2==0&&num2[i]==2)
return false;
if(i%2&&num2[i]%2)
return false;
}
return true;
}
int getstate(int state,int x)
{
int num2[15];
for(int i=0;i<10;i++)
{
num2[i]=state%3;
state/=3;
}
if(num2[x]==0) //前面没出现过,让它变为1
num2[x]++;
else
num2[x]=3-num2[x]; //出现过的话,奇变偶,偶变奇
state=0;
for(int i=9;i>=0;i--)
state=state*3+num2[i];
return state;
}
ll dfs(int len,int state,bool limit)
{
if(len==0)
return check(state);
if(dp[len][state]!=-1&&!limit)
return dp[len][state];
int top=limit?num[len]:9;
ll cnt=0;
for(int i=0;i<=top;i++)
{
cnt+=dfs(len-1,state==0&&i==0?0:getstate(state,i),i==top&&limit); //注意,前导0不能算
}
if(!limit)
dp[len][state]=cnt;
return cnt;
}
ll solve(ll n)
{
int k=0;
while(n)
{
num[++k]=n%10;
n/=10;
}
return dfs(k,0,true);
}
int main()
{
int t;
cin>>t;
memset(dp,-1,sizeof dp);
while(t--)
{
ll l,r;
scanf("%lld%lld",&l,&r);
printf("%lld\n",solve(r)-solve(l-1));
}
return 0;
}