HDU-3709


题目地址:点此传送
题目
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\times2 + 1\times1 = 9\ and \ 9\times1 = 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
2
0 9
7604 24324
Sample Output
10
897
题意

很简单,就是求[a,b]之间满足条件的数有多少个,条件举个例子来说(平衡数),例如4139 这个当中心是3时左边为$1\times1+4\times2=9$右边为$1\times9$,左边等于右边这算是一个平衡数,问你有多少这样的平衡数

思路

数位dp,dp[len][pos][sum] len代表第几位数字,pos代表以pos为中心,sum代表平衡数两边的的差,这道题可以遍历中心pos来进行数位dp,当len<0且sum=0时代表是一个平衡数,sum可以用一种方法表示,到pos的距离乘以的d[i](第i位)

代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
#define ll long long
#define rd(a) scanf("%d",&a)
#define rld(a) scanf("%lld",&a)
#define rs(a) scanf("%s",a)
#define me(a,b) memset(a,b,sizeof(a))
#define pb(a) push_back(a)
const ll maxn=3e5+10;
const ll mod =1e9+7;
const ll inf =0x3f3f3f3f;
const double PI=acos(-1);
int d[20];
ll dp[20][20][2000];
ll dfs(int len,int pos,int limit,int sum){
if(len<0) return sum==0;
if(sum<0) return 0;
if(!limit&&dp[len][pos][sum]!=-1) return dp[len][pos][sum];
int end=limit?d[len]:9;
ll ans=0;
for(int i=0;i<=end;i++){
ans+=dfs(len-1,pos,limit&(i==end),sum+i*(len-pos));
}
if(!limit) dp[len][pos][sum]=ans;
return ans;

}
ll solve(ll x){
int len=0;
while(x){
d[len++]=x%10;
x/=10;
}
ll ans=0;
for(int i=0;i<len;i++)
ans+=dfs(len-1,i,1,0);
return ans-len+1;
}

int main(){

me(dp,-1);
int t;
rd(t);
while(t--){
ll a,b;
rld(a),rld(b);
printf("%lld\n",solve(b)-solve(a-1));

}


return 0;
}
如果对您有帮助,请小小支持一下,您的支持将鼓励我继续创作!
0%