HDU 3709: Balanced Number

平衡数计算算法
本文介绍了一个用于计算指定范围内平衡数数量的算法实现。通过深度优先搜索(DFS)递归方式,考虑数字的每一位,确保从任意位置开始到任意位置结束的数字之和保持平衡。

Balanced Number

 


///@author Sycamore
///@date 8/8/2017
///@ref kuangbin
#include <bits/stdc++.h>
typedef long long L;
using namespace std;
L dp[20][20][2000];
int place[20];
L DFS(int pos, int pivot, int sum, bool limited)
{
	//pos=====================current digit
	//pivot===================current pivot
	//sum======temp sum between pos & pivot
	//limited===whether max(place[digit])==9
	//dp=======solution to the current state
	if (pos == -1)return sum == 0 ? 1 : 0;//all digits visited
	if (sum<0)return 0;//prunning
	if (!limited&&~dp[pos][pivot][sum])//already figured out
		return dp[pos][pivot][sum];
	int end = limited ? place[pos] : 9;
	L res = 0;
	for (int i = 0; i <= end; i++)
		res += DFS(pos - 1, pivot, sum + i*(pos - pivot), limited&&i == end);
	if (!limited)dp[pos][pivot][sum] = res;
	return res;
}
L calc(L n)
{
	int len = 0;
	while (n)
	{
		place[len++] = n % 10;
		n /= 10;
	}
	L res = 0;
	for (int i = 0; i<len; i++)
		res += DFS(len - 1, i, 0, 1);//enumeration by pivots
	return res - (len - 1);//deals with duplicate 0's(00,000,...)
}
int main()
{
	ios::sync_with_stdio(false);
	int T;
	L x, y;
	
	cin >> T;
	while (T--)
	{
		fill(**dp, **(dp+20), -1);
		cin >> x >> y;
		cout<<calc(y) - calc(x - 1)<<endl;
	}
	return 0;
}

 

转载于:https://www.cnblogs.com/zjnu/p/7305768.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值