K - Balanced Numbers SPOJ - BALNUM
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
给你一段区间l-r,问你有多少个数满足偶数出现奇数次,奇数出现偶数次
因为只有0-9这10个数,他们只会有三种状态,0表示没有,1表示出现奇数次,2表示出现偶数次
状态压缩后,十进制表示状态,三进制用以修改
#include <iostream>
#include <cstdio>
#include <cstring>
#define ll long long
using namespace std;
int dp[25][60000],a[25],t[25];
int check(int s) //检查是否满足要求
{
for(int i=0;i<=9;i++)
{
if(s==0) break;
int x=s%3;
s/=3;
if(x==0) continue;
if((i&1)&&x==1) return 0;
if(!(i&1)&&x==2) return 0;
}
return 1;
}
int change(int s,int x)
{
int k=(s/t[x])%3;//!用来判断当前位在state中是几,好方法也适用于二进制
s-=k*t[x];
if(!k) k=1;
else k=3-k; //更新当前位
return s+=k*t[x];
}
int dfs(int pos,int state,bool lead,bool limit)
{
if(pos==0) return check(state);//检查此时状态满不满足,奇数出现偶数次i,偶数出现奇数次
if(!limit&&!lead&&dp[pos][state]!=-1) return dp[pos][state];
int ans=0;
int up=limit?a[pos]:9;
for(int i=0;i<=up;i++)
{
ans+=dfs(pos-1,(lead&&i==0)?0:change(state,i),lead&&i==0,limit&&a[pos]==i); //全为0,状态是0,否则就更新当前位
}
if(!limit&&!lead) dp[pos][state]=ans;
return ans;
}
int solve(ll x)
{
int pos=0;
while(x)
{
a[++pos]=x%10;
x/=10;
}
return dfs(pos,0,1,1);
}
int main()
{
int T;
scanf("%d",&T);
memset(dp,-1,sizeof(dp));
t[0]=1;
for(int i=1;i<=10;i++) t[i]=t[i-1]*3; //初始化三进制上的每一位1,代表多少
while(T--)
{
ll n,m;
scanf("%lld%lld",&n,&m);
printf("%d\n",solve(m)-solve(n-1));
}
return 0;
}