hdu 3709 Balanced Number (数位DP)

来源:互联网 发布:夏易网络 王宇阳 编辑:程序博客网 时间:2024/06/06 16:34

Balanced Number

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 6501    Accepted Submission(s): 3110


Problem 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].
 

Input
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).
 

Output
For each case, print the number of balanced numbers in the range [x, y] in a line.
 

Sample Input
20 97604 24324
 

Sample Output
10897
 

Author
GAO, Yuan
 

题意:
就是叫你找[x,y]中有多少平衡数,平衡数——每个数中有一个轴,使得两边数的力矩到轴相等  4139  3是轴,左边4*2+1*1=9,右边9*1=9,两边相等,所以是平衡数

解析
首先要明白如果一个数是平衡数,那么他就只有一个轴,证:若他有两个轴,当左边轴(此时M左边=M右边)向右移到右边轴时(M左上升,M右下降),因此之后左边一定不等于右边

这样就可用定轴来多次进行数位DP,state就是左边与右边的差值(左边-右边)

#include<cstdio>#include<cstring>typedef long long int ll;int a[100];ll dp[20][1800];  //k:3种操作状况,0:末尾不是1,1:末尾是1,2:含有13  //0为个位,1为十位,。。。。ll dfs(int pos,bool limit,int state,int pivot)   //计算dp[pos][state]即pos-1位是state时满足条件的个数{ll ans=0;if(pos==-1) {return state==0;}if(state<0)return 0;if(!limit&&dp[pos][state]!=-1) return dp[pos][state];   //在非特殊情况下,直接返回之前已经算好的答案int up=limit?a[pos]:9;for(int i=0;i<=up;i++){ans+=dfs(pos-1,limit&&i==up,state+(pos-pivot)*i,pivot);   //state在中枢轴左边的加右边的减,state就是中枢轴左边-右边的差}if(!limit) dp[pos][state]= ans;  //dp只记录普通情况下的值(因为特殊情况都要重新算,不能直接返回)return ans;} /*ll dfs(int pos,bool lim,int state){if(pos==-1) return state==2;if(!lim&&dp[pos][state]!=-1) return dp[pos][state];int up=lim?a[pos]:9;ll ans=0;int tmp_mod,tmp_state;for(int i=0;i<=up;i++){tmp_state=state;if(state==0&&i==4)tmp_state=1;if(state==1&&i!=4)tmp_state=0;if(state==1&&i==9)tmp_state=2;ans+=dfs(pos-1,lim&&i==up,tmp_state);}if(!lim) dp[pos][state]=ans;return ans;}*/ll solve(ll n){ll ans=0;int pos=0;while(n){a[pos++]=n%10;n=n/10;}for(int i=pos-1;i>=0;i--)   //定轴{memset(dp,-1,sizeof(dp));ans+=dfs(pos-1,true,0,i);}return ans-pos+1;  //0被多算了pos-1次}int main(){int t;ll n,m;scanf("%d",&t);while(t--){scanf("%lld%lld",&n,&m);printf("%lld\n",solve(m)-solve(n-1));}return 0;}