F - Balanced Number
题目链接:https://vjudge.net/contest/365059#problem/F
题目大意:给定区间[a,b],求区间内平衡数的个数。所谓平衡数即有一位做平衡点,左右两边数字的力矩想等。
想法:
枚举起点的位置去进行数位DP
#pragma GCC optimize(3,"Ofast","inline")//O3优化 #pragma GCC optimize(2)//O2优化 #include <algorithm> #include <string> #include <string.h> #include <vector> #include <map> #include <stack> #include <set> #include <queue> #include <math.h> #include <cstdio> #include <iomanip> #include <time.h> #include <bitset> #include <cmath> #include <sstream> #include <iostream> #include <cstring> #define LL long long #define ls nod<<1 #define rs (nod<<1)+1 #define pii pair<int,int> #define mp make_pair #define pb push_back #define INF 0x3f3f3f3f #define max(a,b) (a>b?a:b) #define min(a,b) (a<b?a:b) const double eps = 1e-10; const int maxn = 2e5 + 10; const int mod = 1e9 + 7; int sgn(double a){return a < -eps ? -1 : a < eps ? 0 : 1;} using namespace std; LL L,R; int len; int b[20]; LL mem[20][25][2000]; LL dfs(int cur,int pos,int tmp,bool f) { if (cur < 0) return tmp == 0; if (tmp < 0) return 0; if (!f && mem[cur][pos][tmp] != -1) return mem[cur][pos][tmp]; int v = 9; if (f) v = b[cur]; LL ans = 0; for (int i = 0;i <= v;i++) { ans += dfs(cur-1,pos, tmp + (cur-pos)*i,f && (i == v)); } if (!f) mem[cur][pos][tmp] = ans; return ans; } LL solve(LL x) { if (x < 0) return 0; len = 0; while (x) { b[len++] = x % 10; x /= 10; } LL ans = 0; for (int i = 0;i < len;i++) { ans += dfs(len-1,i,0,1); } return ans-len+1; } int main() { ios::sync_with_stdio(0); int T; cin >> T; memset(mem,-1, sizeof(mem)); while (T--) { cin >> L >> R; cout << solve(R) - solve(L-1) << endl; } return 0; }