HDU 3709 Balanced Number(数位DP)
来源:互联网 发布:现货指标公式源码下载 编辑:程序博客网 时间:2024/05/19 20:38
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 rangex,y .
to calculate the number of balanced numbers in a given range
20 97604 24324
10897
Hint
给定区间[a,b],求区间内平衡数的个数。所谓平衡数即有一位做平衡点,左右两边数字的力矩想等。
遍历每一位做为平衡点,进行搜索,sum保存数字乘以距离的和,若sum为0,则说明平衡。
要注意因为遍历了len次,所以0多加了len-1次。
还有个小技巧是当sum<0时就可以直接return了,可以加速。因为,len由大到小的过程中,sum是由大到小的变化,但绝不会小于0,否则就是不能平衡。
#include <bits/stdc++>using namespace std;long long dp[20][20][1540]; /// dp[i][j][k] i表示处理到的数位pos,j是支点,k是力矩和int bit[20];long long dfs(int pos,int pivot,int pre,bool flag){ if(pos==-1)return pre==0; ///出口,也就是正好左右平衡时 if(pre<0)return 0; ///当前力矩为负,剪枝 if(!flag&&dp[pos][pivot][pre]!=-1) return dp[pos][pivot][pre]; int end=flag?bit[pos]:9; long long ans=0; for(int i=0;i<=end;i++) ans+=dfs(pos-1,pivot,pre+i*(pos-pivot),flag&&i==end); ///i*(pos-pivot)写的很巧妙,支点左边加,右边减,支点不算 if(!flag) dp[pos][pivot][pre]=ans; return ans;}long long calc(long long n){ int len=0; while(n) { bit[len++]=n%10; n/=10; } long long ans=0; for(int i=0;i<len;i++) ///遍历每一个中心点 ans+=dfs(len-1,i,0,1); return ans-(len-1);///去掉全0的情况}int main(){// freopen("in.txt","r",stdin);// freopen("out.txt","w",stdout); int T; long long x,y; memset(dp,-1,sizeof(dp));//这个初始化一定别忘记 scanf("%d",&T); while(T--) { scanf("%I64d%I64d",&x,&y); printf("%I64d\n",calc(y)-calc(x-1)); } return 0;}
0 0
- HDU 3709 Balanced Number(数位DP)
- hdu 3709 Balanced Number (数位dp)
- hdu 3709 Balanced Number(数位dp)
- HDU 3709 Balanced Number(数位DP)
- HDU 3709 Balanced Number (数位DP)
- HDU 3709 Balanced Number (数位dp)
- HDU-3709 Balanced Number (数位DP)
- HDU 3709 Balanced Number(数位dp)
- hdu 3709 Balanced Number (数位DP)
- HDU 3709 Balanced Number (数位DP)
- HDU 3709 Balanced Number(数位dp)
- HDU 3709 Balanced Number(数位DP)
- HDU 3709 Balanced Number(数位dp)
- HDU-3709 Balanced Number (数位dp)
- HDU 3709 Balanced Number(数位DP)
- 数位dp HDU 3709 Balanced Number
- Balanced Number - HDU 3709 数位dp
- [数位dp] hdu 3709 Balanced Number
- 数据结构之线性表
- 读书笔记_Effective_C++_条款十一:在operator=中处理自我赋值
- 网格模型obj文件及其纹理解析
- 欢迎使用CSDN-markdown编辑器
- vue2.0学习——组件开发01
- HDU 3709 Balanced Number(数位DP)
- 修改jenkins主目录与cp参数a使用
- Mysql在5.1+事件调度器(Event Scheduler)
- bzoj 1109: [POI2007]堆积木Klo LIS
- druid基本配置和监控使用
- linux 下串口编程VTIME和VMIN的设置
- STL string 类总结
- Centos7部署Kubernetes集群
- jquery对Json的各种遍历方法总结(必看篇)