今天继续写几个数位dp
F - Balanced Number
题目大意:给你一个区间,让你求这个区间之中满足条件的数字有多少。
这个条件:可以选数的一个位为轴,左右到轴的长度乘上那个数字本身相等的数有多少?
我的思路:首先我们要研究这个题目的数字要求,就是找到一个点然后去枚举每一个点是轴,然后我们就再dfs里面搜索
因为我们要求点到轴的力矩,但是我们又不知道力矩的位置,所以我们用一个数来记录到此位置的力矩
这个怎么记录呢?比如说数字abcdef
第一次就是a,第二次是a*2+b 第三次是a*3+b*2+c。。。。
所以我们需要有一个来记录这个力矩,还需要有一个数来记录 a a+b a+b+c....
这个时候就很好求了。
所以这个dp我是这么定义的 dp[i][j][k][h]表示到第 i 位 轴为 j 力矩为 k 数字之和为 h
但是自己敲了之后发现有问题
首先就是这个数组开的太大了,其次就是这个状态定义的唯一不唯一很难确定。
我对于这个dp数组是真的无奈,不知道该怎么去定义,有时候定义多了,有时候定义少了。
状态是不是唯一真的很难去判断。
看了题解,题解是这么定义的,
dp[i][j][k] 表示第 i 为以第 j 位 是否满足条件,满足k==0,不满足k!=0
这个状态一定义下来,就很好写这个dp了。
#include <cstdio> #include <cstdlib> #include <cstring> #include <queue> #include <algorithm> #include <vector> #include <iostream> #define inf 0x3f3f3f3f3f3f3f3f using namespace std; const int maxn = 1010; const int mod = 2520; typedef long long ll; ll dp[20][20][2000]; int a[maxn]; ll dfs(int pos,int sta,int num,bool limit) { if (pos == -1) return num == 0; if (num < 0) return 0; if (!limit&&dp[pos][sta][num] != -1) return dp[pos][sta][num]; int up = limit ? a[pos] : 9; ll ans = 0; for(int i=0;i<=up;i++) { ans += dfs(pos - 1, sta, num + (pos - sta)*i, limit && (i == up)); } if (!limit) dp[pos][sta][num] = ans; return ans; } ll solve(ll x) { if (x < 0) return 0; int pos = 0; while(x) { a[pos++] = x % 10; x /= 10; } ll ans = 0; for(int i=0;i<pos;i++) ans += dfs(pos - 1, i, 0,1); return ans - pos + 1; } int main() { int t; cin >> t; memset(dp, -1, sizeof(dp)); while(t--) { ll a, b; scanf("%lld%lld", &a, &b); ll ans = solve(b) - solve(a - 1); printf("%lld\n", ans); } return 0; }