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 题意:奇数个数为偶数,偶数个数为奇数。 用三进制来表示0-9的状态,0为没有,1为奇数个,2为偶数个。
3^10约为60000。
注意判断前导零。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll; ll a[],p[],st[][];
ll dp[][]; ll dfs(int pos,int sta,bool lead,bool limit){ if(pos==-){
for(int i=;i<=;i+=){
if(st[sta][i]==) return ;
}
for(int i=;i<=;i+=){
if(st[sta][i]==) return ;
}
return ;
}
if(!lead&&!limit&&dp[pos][sta]>-) return dp[pos][sta];
int up=limit?a[pos]:;
ll cnt=;
for(int i=;i<=up;i++){
if(i==&&lead){
cnt+=dfs(pos-,sta,lead&&i==,limit&&i==a[pos]);
}
else if(st[sta][i]==){
cnt+=dfs(pos-,sta-p[i],lead&&i==,limit&&i==a[pos]);
}
else{
cnt+=dfs(pos-,sta+p[i],lead&&i==,limit&&i==a[pos]);
}
}
if(!lead&&!limit) dp[pos][sta]=cnt;
return cnt;
}
ll solve(ll x){
int pos=;
while(x){
a[pos++]=x%;
x/=;
}
return dfs(pos-,,true,true);
}
int main()
{
int t;
ll l,r;
scanf("%d",&t);
memset(dp,-,sizeof(dp));
p[]=;
for(int i=;i<=;i++){
p[i]=p[i-]*;
}
for(int i=;i<p[];i++){
int ii=i,c=-;
while(ii){
c++;
st[i][c]=ii%;
ii/=;
}
}
while(t--){
scanf("%lld%lld",&l,&r);
printf("%lld\n",(solve(r)-solve(l-)));
}
return ;
}