HDOJ 3709 Balanced Number (数位DP)
题意:求[x , y]中有多少个平衡数。
平衡数:选定一位作为支点,若左右的力矩平衡则该数是平衡数,否则不是。For example, 4139 is a balanced number with pivot fixed at 3. The torqueses are 4*2 + 1*1 = 9 and 9*1 = 9

#include <stdio.h> #include <string.h> #define N 19 #define M 1378 typedef __int64 LL; LL dp[N][N][M]; int digit[N]; LL dfs(int pos,int o,int sum,int f) { if(sum<0) return 0; if(pos==-1) return sum==0; if(!f&&dp[pos][o][sum]!=-1) return dp[pos][o][sum]; LL ret=0; int max=f?digit[pos]:9; for(int i=0;i<=max;i++) { ret+=dfs(pos-1,o,sum+(pos-o)*i,f&&i==max); } if(!f) dp[pos][o][sum]=ret; return ret; } LL cal(LL x) { int pos=0; while(x) { digit[pos++]=x%10; x/=10; } LL ret=0; for(int o=0;o<pos;o++) { ret+=dfs(pos-1,o,0,1); } return ret-pos+1; } int main() { int t; memset(dp,-1,sizeof(dp)); scanf("%d",&t); while(t--) { LL x,y; scanf("%I64d%I64d",&x,&y); printf("%I64d\n",cal(y)-cal(x-1)); } return 0; }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步