hdu3709

链接:hdu3709

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 42 + 11 = 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

    2
    0 9
    7604 24324

    Sample Output

    10
    897

    题解

  • 模板题
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
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#define rep(i,l,n) for(register int i=l;i<n;++i)
#define ll long long
using namespace std;
const int N=22;
ll dp[N][N][2000];//第i位,枢轴为j的时候和为k时共有多少种情况满足符合要求
int a[N];

ll dfs(int len,int pos,int limit,int sta){
if(len==-1)return sta?0:1;
if(sta<0)return 0;
if(!limit&&dp[len][pos][sta]!=-1)return dp[len][pos][sta];
int up=limit?a[len]:9;
ll tmp=0;
rep(i,0,up+1){
tmp+=dfs(len-1,pos,limit&&i==a[len],sta+i*(len-pos));
}
if(!limit)dp[len][pos][sta]=tmp;
return tmp;
}


ll solve(ll x){
int cnt=0;
while(x){
a[cnt++]=x%10;
x/=10;
}
ll ans=0;
rep(i,0,cnt){
ans+=dfs(cnt-1,i,1,0);
}
return ans-cnt+1;
}

int main(){
ll l,r;
int T;
scanf("%d",&T);
memset(dp,-1,sizeof(dp));
while(T--){
scanf("%lld%lld",&l,&r);
printf("%lld\n",solve(r)-solve(l-1));
}
return 0;
}