HDU-3709 Balanced Number

http://acm.hdu.edu.cn/showproblem.php?pid=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*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].

 

题意:对于某正整数,如果以该数的某位为中心,两边距离与数字之积相加之后相等,则该数为平衡数,例如4139,4*2 + 1*1 = 9 and 9*1 = 9,该数是平衡数,求区间内平衡数的个数。

思路:首先最关键的,要明白:对于一个非0的数,最多可能有一个中间点,不可能一个数有两个中心点。

这是为什么呢?假设有两个中心点,对于左边中心点来说,其左右加权相等,那么想象中心点向右移的过程中,左边加权一定增大,右边减少(一个特殊情况是x0000这样的,左边增大,右边不变),总之一个数(非0)最多有1个中心点。

对于确定的中心点,判断一个数是不是平衡数,就把距离考虑上正负,最后加权判断和是不是0就行了。

那么我们枚举中心点位置,状态是(第pos位,中心点是mid位,当前加权和是sum)

每一个中心点都计入了一次0,故[0,x]的个数是Σdfs-pos+1

#include<bits/stdc++.h>
using namespace std;
#define ll long long

ll T,A,B;
ll a[20],dp[20][20][4000];

ll dfs(ll pos,ll mid,ll sum,bool limit)
{
	if(pos==-1)return sum==0;
	if(!limit&&dp[pos][mid][sum]!=-1)return dp[pos][mid][sum];
	int up= (limit?a[pos]:9);
	ll ans=0;
	for(int i=0;i<=up;i++)
	{
		ans+=dfs(pos-1,mid,sum+(pos-mid)*i,limit&&i==a[pos]);
	}
	if(!limit)dp[pos][mid][sum]=ans;
	return ans;
}

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

int main()
{
//	freopen("input.in","r",stdin);
	memset(dp,-1,sizeof(dp));
	cin>>T;
	while(T--)
	{
		cin>>A>>B;
		if(A)cout<<solve(B)-solve(A-1)<<endl;
		else cout<<solve(B)<<endl;
	}
	return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值