[SPOJ BALNUM]Balanced Numbers(数位dp,状态压缩)
题目链接:http://www.spoj.com/problems/BALNUM/en/
题意:求区间内数字满足“奇数各数出现偶数次,偶数各数出现奇数次”的数字的个数。
数位dp,dp(l,s)表示长度为l的时候0~9各出现的状态情况,因为可能有未出现的情况,如果这个s用二进制保存的话那么未出现的偶数可能会因为0而出现误判,所以应该多一个状态,就用三进制。0表示未出现,1表示出现了奇数次,2表示出现了偶数次。这个三进制我写半天真是弱智。。。
1 #include <bits/stdc++.h> 2 using namespace std; 3 #define fr first 4 #define sc second 5 #define cl clear 6 #define BUG puts("here!!!") 7 #define W(a) while(a--) 8 #define pb(a) push_back(a) 9 #define Rint(a) scanf("%d", &a) 10 #define Rll(a) scanf("%I64d", &a) 11 #define Rs(a) scanf("%s", a) 12 #define Cin(a) cin >> a 13 #define FRead() freopen("in", "r", stdin) 14 #define FWrite() freopen("out", "w", stdout) 15 #define Rep(i, len) for(int i = 0; i < (len); i++) 16 #define For(i, a, len) for(int i = (a); i < (len); i++) 17 #define Cls(a) memset((a), 0, sizeof(a)) 18 #define Clr(a, x) memset((a), (x), sizeof(a)) 19 #define Full(a) memset((a), 0x7f7f7f, sizeof(a)) 20 #define lrt rt << 1 21 #define rrt rt << 1 | 1 22 #define pi 3.14159265359 23 #define RT return 24 #define lowbit(x) x & (-x) 25 #define onecnt(x) __builtin_popcount(x) 26 typedef long long LL; 27 typedef long double LD; 28 typedef unsigned long long ULL; 29 typedef pair<int, int> pii; 30 typedef pair<string, int> psi; 31 typedef pair<LL, LL> pll; 32 typedef map<string, int> msi; 33 typedef vector<int> vi; 34 typedef vector<LL> vl; 35 typedef vector<vl> vvl; 36 typedef vector<bool> vb; 37 38 const int maxn = 33; 39 const int maxm = 59050; 40 int digit[maxn]; 41 LL l, r; 42 LL dp[maxn][maxm][2]; 43 44 int mul(int x, int y) { 45 int ret = 1; 46 while(y) { 47 if(y & 1) ret *= x; 48 x *= x; 49 y >>= 1; 50 } 51 return ret; 52 } 53 54 bool ok(int s) { 55 int l = -1, bit; 56 while(s) { 57 ++l; 58 bit = s % 3; 59 if((l & 1) && bit == 1) return 0; 60 if((l & 1) != 1 && bit == 2) return 0; 61 s /= 3; 62 } 63 return 1; 64 } 65 66 int add(int s, int i) { 67 int ts = s, ti = i; 68 while(ti--) ts /= 3; 69 int bit = ts % 3; 70 if(bit < 2) return s + mul(3, i); 71 return s - mul(3, i); 72 } 73 74 LL dfs(int l, int s, bool fz, bool flag) { 75 if(l == 0) { 76 if(ok(s)) return 1; 77 return 0; 78 } 79 if(!flag && ~dp[l][s][fz]) return dp[l][s][fz]; 80 LL ret = 0; 81 int pos = flag ? digit[l] : 9; 82 Rep(i, pos+1) { 83 if(fz && i == 0) { 84 ret += dfs(l-1, s, fz&&(i==0), flag&&(i==pos)); 85 } 86 else { 87 ret += dfs(l-1, add(s, i), fz&&(i==0), flag&&(i==pos)); 88 } 89 } 90 if(!flag) dp[l][s][fz] = ret; 91 return ret; 92 } 93 94 LL f(LL x) { 95 int pos = 0; 96 while(x) { 97 digit[++pos] = x % 10; 98 x /= 10; 99 } 100 return dfs(pos, 0, true, true); 101 } 102 103 signed main() { 104 //FRead(); 105 int T; 106 Rint(T); 107 Clr(dp, -1); 108 W(T) { 109 cin >> l >> r; 110 cout << f(r) - f(l-1) << endl; 111 } 112 RT 0; 113 }