数位dp模版题(杠杆数/平衡数)
洛谷:p1831杠杆题
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; long long int num[1004] = {}; long long int dp[20][20][2005] = {}, l, r; long long int dfs(long long int pos,long long int x,bool flag,bool lim, long long int num1) { if(!pos) return num1 == 0; if(!lim && dp[pos][x][num1] != -1) return dp[pos][x][num1]; long long int maxx = lim ? num[pos] : 9, ans = 0; for(int i = 0;i <= maxx;i++) { if(flag) ans += dfs(pos-1,x,flag && i == 0,lim && i == maxx,i*(pos - x)); else { ans += dfs(pos-1,x,flag && i == 0,lim && i == maxx,num1 + i*(pos - x)); } } if(!lim) dp[pos][x][num1] = ans; return ans; } long long int solve(long long int x) { long long int ans = 0, cnt = 0; while(x) num[++cnt] = x % 10, x/= 10; for(int i = 1;i <= cnt;i++) { ans += dfs(cnt,i,1,1,0); } return ans-cnt+1; } int main() { memset(dp,-1,sizeof(dp)); scanf("%lld%lld", &l, &r); if(!l) printf("%lld\n", solve(r)); else printf("%lld\n", solve(r) - solve(l-1)); return 0; }