HDU 3709 Balanced Number (数位DP 枚举)

来源:互联网 发布:怎样购买域名和空间 编辑:程序博客网 时间:2024/05/29 17:52

题目地址:点击打开链接


思路:

首先要分析出,对于某个非 0 的 number,最多可能有一个 pivot 的位置。

证明:如果有两个这样的位置,将左边位置移动到右边时,左边的 sigma 一定增大,右边的 sigma 最多保证不减,不可能增大,故不可能再次相等。

于是可以枚举这样的位置,然后分类统计求和。


然后枚举支点的位置。dfs里的d指的是当前支点的枚举位置,那么他们之间的距离就是pos-d了,再乘以这一个点所有可能的数值,然后这个dfs再深入下去继续找,这里注意,如果sum<0直接返回0就行,一方面是数组下表不能负数,另一方面一开始sum是正的,如果能达到条件最后一定是0,是负的说明不可能


最后注意0会重复计算


代码:

#include<iostream>#include<cstdio>#include<cstring>using namespace std;typedef long long ll;const int maxn = 5e3+5;ll dp[20][20][maxn], a[maxn];ll dfs(int pos, int d, int sum, int limit){    if(pos == -1) return sum==0;    if(sum < 0) return 0;    if(!limit && dp[pos][d][sum] != -1) return dp[pos][d][sum];    int up = limit ? a[pos] : 9;    ll tmp = 0;    for(int i = 0; i <= up; i++)        tmp += dfs(pos-1, d, sum+(pos-d)*i, limit&&i==a[pos]);    if(!limit) dp[pos][d][sum] = tmp;    return tmp;}ll solve(ll x){    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(void){    int t;    memset(dp, -1, sizeof(dp));    cin >> t;    while(t--)    {        ll x, y;        scanf("%lld%lld", &x, &y);        printf("%lld\n", solve(y)-solve(x-1));    }    return 0;}

Balanced Number

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 5241    Accepted Submission(s): 2510


Problem Description
A balanced number is a non-negative integer that can be balanced if a pivot is placed at some digit. More specifically, imagine each digit as a box with weight indicated by the digit. When a pivot is placed at some digit of the number, the distance from a digit to the pivot is the offset between it and the pivot. Then the torques of left part and right part can be calculated. It is balanced if they are the same. A balanced number must be balanced with the pivot at some of its digits. For example, 4139 is a balanced number with pivot fixed at 3. The torqueses are 4*2 + 1*1 = 9 and 9*1 = 9, for left part and right part, respectively. It's your job
to calculate the number of balanced numbers in a given range [x, y].
 

Input
The input contains multiple test cases. The first line is the total number of cases T (0 < T ≤ 30). For each case, there are two integers separated by a space in a line, x and y. (0 ≤ x ≤ y ≤ 1018).
 

Output
For each case, print the number of balanced numbers in the range [x, y] in a line.
 

Sample Input
20 97604 24324
 

Sample Output
10897
 

0 0
原创粉丝点击