hdu3709 Balanced Number
Posted ovo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu3709 Balanced Number相关的知识,希望对你有一定的参考价值。
Balanced Number
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
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].
to calculate the number of balanced numbers in a given range [x, y].
题目先给出平衡数的概念:数n以数n中的某个位为支点,每个位上的数权值为(数字xi*(posi - 支点的posi)),如果数n里有一个支点使得所有数权值之和为0那么她就是平衡数。比如4139,以3为支点,左边 = 4 * (4 - 2) + 1 * (3 - 2) = 9,右边 = 9 * (1 - 2) = -9,左边加右边为0,所以4139是平衡数。现在给出一个区间[l,r],问区间内平衡数有多少个?
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
Recommend
Solution
数位dp
dp[i][j][k]表示考虑到第i位,j为支点,当前权值和为k的数的个数.
先枚举一个支点,再dp
注意全为0的情况被多算了,要减去
#include<algorithm> #include<iostream> #include<cstring> #include<cstdlib> #include<cstdio> #include<cmath> #define lo long long using namespace std; int a[23]; lo dp[23][23][3011]; inline long long read() { register long long ans=0,f=1;char ch=getchar(); while(!isdigit(ch)) {if(ch==‘-‘) f=-1;ch=getchar();} while(isdigit(ch)) {ans=ans*10+ch-‘0‘;ch=getchar();} return ans*f; } lo dfs(int wi,int mid,int v,bool lim) { if(wi<1) return v==0; if(!lim&&dp[wi][mid][v]>-1) return dp[wi][mid][v]; int o=lim? a[wi]:9; lo ans=0; for(int i=0;i<=o;i++) ans+=dfs(wi-1,mid,v+(wi-mid)*i,lim&&i==a[wi]); if(!lim) dp[wi][mid][v]=ans; return ans; } lo sol(lo x) { if(x<0) return 0; int w=0;lo ans=0; while(x) { a[++w]=x%10; x/=10; } for(int i=1;i<=w;i++) ans+=dfs(w,i,0,1); return ans-w+1; ////全是0的情况被多算了 } int main() { int t;lo l,r; t=read(); memset(dp,-1,sizeof(dp)); while(t--) { l=read();r=read(); printf("%lld\n",sol(r)-sol(l-1)); } return 0; }
以上是关于hdu3709 Balanced Number的主要内容,如果未能解决你的问题,请参考以下文章
HDU - 3709 - Balanced Number(数位DP)
HDU 3709 Balanced Number (数位DP)