题目链接:
HDU 3709 Balanced Number
题意:
如果一个数字以某一位为平衡点左右力矩相等,则称该数字为Balanced Number。求区间 [L,R] 中Balanced Number的数量。
数据范围: 0≤L≤R≤1018
分析
枚举平衡点并记录平衡点左右力矩之差为 sum ,这样子才能记忆化。还要注意0的情况。
Code
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
typedef long long ll;int digit[20];
ll dp[20][20][4000];ll dfs(int pos, int pivot, int sum, int limit)
{if (sum < 0 || sum > pivot * (pivot + 1) / 2 * 9) return 0;if (pos == -1) return sum == 0;if (!limit && dp[pos][pivot][sum] != -1) return dp[pos][pivot][sum];int last = limit ? digit[pos] : 9;ll ret = 0;for (int i = 0; i <= last; ++i) {int next_sum = sum + i * (pos - pivot);ret += dfs(pos - 1, pivot, next_sum, limit && i == last);}if (!limit) dp[pos][pivot][sum] = ret;return ret;
}ll solve(ll x)
{if (x < 0) return 0;else if (x == 0) return 1;memset(digit, 0, sizeof(digit));int len = 0;while (x) {digit[len++] = x % 10;x /= 10;}ll ret = 0;for (int i = 0; i < len; ++i) {ret += dfs(len - 1, i, 0, 1);}return ret - (len - 1); // 把0算了len次
}int main()
{int T;ll L, R;scanf("%d", &T);while (T--) {memset(dp, -1, sizeof(dp));scanf("%lld%lld", &L, &R);printf("%lld\n", solve(R) - solve(L - 1));}return 0;
}