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: 1474
题意:给你一个区间,问这个区间内满足十进制每一位上 偶数出现基础次,奇数出现偶数次的数有多少个。
0-9的每个数可以有三种状态,0-未出现过 1-出现奇数次 2-出现偶数次,那么以三进制进行状态压缩的话最多只有
3^10个状态,将每个数压缩成三进制进行dfs就可以很好的解决了。
#include<stdio.h> #include<algorithm> #include<string.h> #include<math.h> using namespace std; #define ll long long const int maxm = 25; ll dp[maxm][60006]; int d[maxm]; bool judge(int n) { for (int i = 0;i <= 9;i++) { if (i % 2 == 0 && n % 3 == 2) return false; if (i % 2 == 1 && n % 3 == 1) return false; n /= 3; } return true; } int change(int s, int n) { int a = s, b = n; while (b--) a /= 3; if (a % 3 < 2) s += pow(3.0, n); else s -= pow(3.0, n); return s; } ll dfs(int len, int num, int flag) { if (len < 0) return judge(num); if (!flag&&dp[len][num] != -1) return dp[len][num]; int k = flag ? d[len] : 9; ll ans = 0; for (int i = 0;i <= k;i++) ans += dfs(len - 1, num == 0 && i == 0 ? 0 : change(num, i), flag&&i == k); if (!flag) dp[len][num] = ans; return ans; } ll solve(ll n) { int len = 0; while (n) d[len++] = n % 10, n /= 10; return dfs(len - 1, 0, 1); } int main() { ll a, b, t; memset(dp, -1, sizeof(dp)); scanf("%lld", &t); while (t--) { scanf("%lld%lld", &a, &b); printf("%lld\n", solve(b) - solve(a - 1)); } return 0; }