F - Balanced Number

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <string>
 6 #include <map>
 7 #include <cmath>
 8 #include <vector>
 9 
10 #define Faster ios::sync_with_stdio(false),cin.tie(0)
11 #define Read freopen("in.txt","r",stdin),freopen("out.txt","w",stdout)
12 #define Close fclose(stdin),fclose(stdout)
13 const int maxn = 1e4 + 5;
14 using namespace std;
15 const int MOD = 1e9+7;
16 typedef long long ll;
17 
18 ll dp[20][20][2000];
19 int a[20];
20 
21 ll dfs(int pos, int cut, int sum, bool limit){
22     if (pos == -1) return sum?0:1;    //sum为0的时候说明是平衡的
23     if (sum < 0) return 0;    //sum < 0 就肯定不平衡了返回0
24     if(!limit && dp[pos][cut][sum] != -1)
25         return dp[pos][cut][sum];
26     int up = limit?a[pos]:9;
27     ll ans = 0;
28     for(int i = 0; i <= up;i++){
29         ans += dfs(pos-1, cut, sum + (pos-cut)*i, limit && a[pos] == i);
30     }
31     if(!limit)
32         dp[pos][cut][sum] = ans;
33     return ans;
34 }
35 
36 ll solve(ll x){
37     int pos = 0;
38     while(x){
39         a[pos++] = x%10;
40         x /= 10;
41     }
42     ll ans = 0;
43     for(int i = 0;i < pos;i++){
44         ans += dfs(pos-1, i, 0, true);
45     }
46     return ans - pos + 1;
47     //因为0多加了(pos - 1)次
48 }
49 
50 int main(){
51     Faster;
52     int t;
53     cin >> t;
54     memset(dp, -1, sizeof(dp));
55     while(t--){
56         ll l, r;
57         cin >> l >> r;
58         ll ans = solve(r) - solve(l-1);
59         cout << ans << endl;
60     }
61     return 0;
62 }

猜你喜欢

转载自www.cnblogs.com/jaydenouyang/p/9141746.html