to calculate the number of balanced numbers in a given range [x, y].
InputThe input contains multiple test cases. The first line is the total number of cases T (0 < T ≤ 30). For each case, there are two integers separated by a space in a line, x and y. (0 ≤ x ≤ y ≤ 10 18).OutputFor each case, print the number of balanced numbers in the range [x, y] in a line.Sample Input
2 0 9 7604 24324
Sample Output
10 897
题意:一个数,定一个支点,力矩相等为平衡数。
题解:数位dp,f[i][j][k]表示i为,j位为支点,k为当前力矩。
1 #include<cstring> 2 #include<cmath> 3 #include<algorithm> 4 #include<iostream> 5 #include<cstdio> 6 #define ll long long 7 using namespace std; 8 9 ll f[21][21][2007],l,r; 10 int a[21],n,cnt; 11 12 ll dfs(int wei,int zd,int lj,bool flag) 13 { 14 if (wei==0) return lj==0; 15 if (lj<0) return 0; 16 if (!flag&&f[wei][zd][lj]!=-1) return f[wei][zd][lj]; 17 ll res=0; 18 int ed; 19 if (flag) ed=a[wei]; 20 else ed=9; 21 for (int i=0;i<=ed;i++) 22 res+=dfs(wei-1,zd,lj+(wei-zd)*i,flag&&i==ed); 23 if (!flag) f[wei][zd][lj]=res; 24 return res; 25 } 26 ll solve(ll x) 27 { 28 cnt=0; 29 while(x) 30 { 31 a[++cnt]=x%10; 32 x/=10; 33 } 34 ll ans=0; 35 for (int i=1;i<=cnt;i++) 36 ans+=dfs(cnt,i,0,1); 37 return ans-(cnt-1); 38 } 39 int main() 40 { 41 int cas;scanf("%d",&cas); 42 memset(f,-1,sizeof(f)); 43 while(cas--) 44 { 45 scanf("%lld%lld",&l,&r); 46 printf("%lld\n",solve(r)-solve(l-1)); 47 } 48 }