Balanced numbers have been used by mathematicians for centuries. A positive integer is considered a balanced number if:c++
1) Every even digit appears an odd number of times in its decimal representationgit
2) Every odd digit appears an even number of times in its decimal representationapp
For example, 77, 211, 6222 and 112334445555677 are balanced numbers while 351, 21, and 662 are not.ide
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.spa
The first line contains an integer T representing the number of test cases.code
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 blog
For each test case, you need to write a number in a single line: the amount of balanced numbers in the corresponding intervalci
Input: 2 1 1000 1 9
Output: 147 4
题意:求l-r之间13579是偶数个,24680是奇数个的数的个数
题解:状压压一下每一位是奇是偶,1表示奇,2表示偶,0表示没取
dp[pos][sta]表示第pos位以前sta的数有几个
最基础的数位DP写法
记得去一下前导零
代码以下:
#include<bits/stdc++.h> using namespace std; int n; long long l,r; long long dp[23][60000][2],a[23],b3[12]; int gg(int x,int pos) { return (x%b3[pos+1])/b3[pos]; } inline int check(int sta) { for(int i=1;i<=9;i+=2) { if(gg(sta,i)==1) return 0; } for(int i=0;i<=8;i+=2) { if(gg(sta,i)==2) return 0; } return 1; } long long dfs(int pos,int sta,int lim,int lim2) { if(pos<=0) return check(sta); if(!lim&&dp[pos][sta][lim2]!=-1) return dp[pos][sta][lim2]; int up=lim?a[pos]:9; long long res=0; int nextsta; for(int i=0;i<=up;i++) { if(!lim2&&i==0) { res+=dfs(pos-1,sta,lim&&i==a[pos],lim2); } else { if(gg(sta,i)!=2) nextsta=sta+b3[i]; else nextsta=sta-b3[i]; res+=dfs(pos-1,nextsta,lim&&i==a[pos],lim2|1); } } if(!lim) dp[pos][sta][lim2]=res; return res; } long long get(long long x) { memset(dp,-1,sizeof(dp)); int cnt=0; while(x) { a[++cnt]=x%10; x/=10; } return dfs(cnt,0,1,0); } int main() { b3[0]=1; for(int i=1;i<=11;i++) b3[i]=b3[i-1]*3; scanf("%d",&n); while(n--) { scanf("%lld%lld",&l,&r); printf("%lld\n",get(r)-get(l-1)); } }