去HDU测测你的 Balanced number [Submit]
Balanced NumberTime Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 9702 Accepted Submission(s): 4616 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
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 |
第二版的b-number 是让你去找一个平衡点,使得这个点的∑(前面的数字*数字到平衡点的距离)=∑(后面的数字*数字到平衡点的距离),类似于我们学过的杠杆原理,让你去找支点,如果存在这样的支点,那么这个数就是 balanced number
一眼望去就知道这是一个数位dp的题目,这里我们就设一个dp数组
dp[pos][zhou][sum]====pos是指当前的枚举位置,zhou使我们假设的轴即平衡位置,sum是 数字*(pos-sum)可以看出来,如果是平衡数的话,肯定sum==0成立
首先我们要枚举轴的位置,然后再去数位dp枚举数字,判断这个数字中有没有轴
这道题我遇到了两个坑点
for(ll i=0;i<cnt;i++)
ans+=dfs(cnt-1,i,0,1);
第一个就是 0这个数字是一个 balanced number,但是当他给你一串0 的时候,你就会枚举cnt次,但是他却只有一个零 也就是说你多枚举了 cnt-1次,你需要减掉他
for(ll i=0;i<=up;i++)
res+=dfs(pos-1,zhou,sum+(pos-zhou)*i,i==a[pos]&&limit);
再一个就是dfs里面的枚举因为是从高位枚举,所以pos会大于等于zhou,我一开始就是不小心写成了 sum+(zhou-pos)*i,导致了样例都过不去,因为sum是数组dp的一个下标,下标变成负的那还不乱套了???
就那么多problem,剩下的就是我的AC代码了
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#define ll long long
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const ll inf=0x3f3f3f3f;
const ll mm=20;
ll a[mm];
ll dp[mm][mm][2000];
// pos,zhou,sum
ll dfs(ll pos,ll zhou,ll sum,ll limit){
if(sum<0)return 0;
if(pos<0)return sum==0;
if(!limit&&dp[pos][zhou][sum]!=-1)
return dp[pos][zhou][sum];
ll res=0;
ll up=limit?a[pos]:9;
for(ll i=0;i<=up;i++)
res+=dfs(pos-1,zhou,sum+(pos-zhou)*i,i==a[pos]&&limit);//
if(!limit)dp[pos][zhou][sum]=res;
return res;
}
ll solve(ll x){
ll cnt=0;
while(x){
a[cnt++]=x%10;
x/=10;
}
ll ans=0;
for(ll i=0;i<cnt;i++)
ans+=dfs(cnt-1,i,0,1);
return ans-cnt+1;//去重
}
int main()
{
ll t;
cin>>t;
mem(dp,-1);
while(t--){
ll x,y;
cin>>x>>y;
ll res=solve(y)-solve(x-1);
cout<<res<<endl;
}
return 0;
}