zoj3416 数位DP
来源:互联网 发布:sas安装数据sid无效 编辑:程序博客网 时间:2024/05/29 05:02
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 casesT (0 <T ≤ 30). For each case, there are two integers separated by a space in a line,x andy. (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
题意:给出两个数a,b算[a,b]范围内有多少个平衡数,如4139,当它以3为轴时,左边有4*2+1*1=9,右边为1*9=9,所以左右相等
思路:只要想到怎么计算他们的和其实就不难了,只要枚举轴在第几位,然后把每一位到轴的指加上,轴左边为正右边为负,当所有位累加完之后,只要判断是否抵消和为0,即可。最后只要减去多余的,因为0会重复算,0只需要算一次,用数位dp会算len次,即是数字的长度,减去len-1即是最后答案
#include<cstdio>#include<cstring>#include<iostream>using namespace std;long long dp[20][20][2000];int s[20];long long dfs(int now,int sum,int cur,int flag){if(now<=0) return sum==0;if(!flag&&dp[now][cur][sum]!=-1)return dp[now][cur][sum];int num=(flag?s[now]:9);long long ans=0;for(int i=0;i<=num;i++){int temp=sum+(now-cur)*i;if(temp>=0)ans+=dfs(now-1,temp,cur,flag&&i==num);}if(!flag)dp[now][cur][sum]=ans;return ans;}long long slove(long long x){if(x==-1)return 0;int k=0;while(x){s[++k]=x%10;x/=10;}long long ans=0;for(int i=1;i<=k;i++)ans+=dfs(k,0,i,1);ans=ans-k+1;return ans;}int main(void){long long a,b;int t;scanf("%d",&t);memset(dp,-1,sizeof(dp));while(t--){scanf("%lld%lld",&a,&b);printf("%lld\n",slove(b)-slove(a-1));}return 0;}
- zoj3416 数位DP
- 数位DP--ZOJ3416(Balanced Number)
- 数位dp
- 数位DP
- 数位DP
- 数位dp
- 数位dp
- 数位dp
- 数位DP
- 数位dp
- 数位DP
- 【数位DP】
- 数位DP
- 数位dp
- 数位dp
- 数位DP
- 数位DP
- 数位dp
- 【Android Studio快捷键】之代码提示
- HDU--1584--蜘蛛牌--深搜版本
- 有意思的博弈论
- [网络] SOCKET, TCP/UDP, HTTP, FTP
- Detour使用说明
- zoj3416 数位DP
- oracle的游标用法
- xcode_6_beta_5下载
- 新导入的工程出现乱码问题 及其 R文件没有生成 解决方案.
- 针对ie6下页面跳转问题详解
- 开源分词工具
- PreparedStatement的用法
- 还是DLL引用问题。。
- c#怎么判断输入法