标签:des style blog color os strong io for
Description
A balanced number is a non-negative integer that can be balanced if a pivot is placed at some digit. More specifically, imagine each digit as a box with weight indicated by the digit. When a pivot is placed at some digit of the number, the distance from a digit to the pivot is the offset between it and the pivot. Then the torques of left part and right part can be calculated. It is balanced if they are the same. A balanced number must be balanced with the pivot at some of its digits. For example, 4139 is a balanced number with pivot fixed at 3. The torqueses are 4*2 + 1*1 = 9 and 9*1 = 9, for left part and right part, respectively. It‘s your job to calculate the number of balanced numbers in a given range [ x, y].
The 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 ≤ 1018).
For each case, print the number of balanced numbers in the range [x, y] in a line.
2 0 9 7604 24324
10 897
数位dp
表示暂时还不明白为什么这样搜索不会超时。。
#include<cstdio> #include<cstring> long long f[20][20][2000]; int a[20]; long long dfs(int pos,int z,int l,bool pd){ if(pos<=0) return l==0; if(l<0) return 0; if(!pd&&f[pos][z][l]!=-1) return f[pos][z][l]; int i,j,k,en; en=pd?a[pos]:9; long long ans=0; for(i=0;i<=en;i++) ans+=dfs(pos-1,z,l+(pos-z)*i,pd&&i==en); if(!pd) f[pos][z][l]=ans; return ans; } long long sum(long long x){ int i,n=0; while(x){ a[++n]=x%10; x=x/10; } long long ans=0; for(i=n;i>0;i--) ans+=dfs(n,i,0,1); return ans-n+1; } int main() { int tt; long long x,y; scanf("%d",&tt); while(tt--){ scanf("%lld%lld",&x,&y); memset(f,-1,sizeof(f)); printf("%lld\n",sum(y)-sum(x-1)); } return 0; }
Balanced Number (数位dp),布布扣,bubuko.com
标签:des style blog color os strong io for
原文地址:http://www.cnblogs.com/Mathics/p/3868422.html