SPOJ - BALNUM Balanced Numbers 数位dp+状态压缩

Balanced numbers have been used by mathematicians for centuries. A positive integer is considered a balanced number if:

1)      Every even digit appears an odd number of times in its decimal representation

2)      Every odd digit appears an even number of times in its decimal representation

For example, 77, 211, 6222 and 112334445555677 are balanced numbers while 351, 21, and 662 are not.

Given an interval [A, B], your task is to find the amount of balanced numbers in [A, B] where both A and B are included.

Input

The first line contains an integer T representing the number of test cases.

A test case consists of two numbers A and B separated by a single space representing the interval. You may assume that 1 <= A <= B <= 1019 

Output

For each test case, you need to write a number in a single line: the amount of balanced numbers in the corresponding interval

Example

Input:
2
1 1000
1 9
Output:
147

4

题意:给你一个区间,问这个区间内满足十进制每一位上 偶数出现基础次,奇数出现偶数次的数有多少个。

0-9的每个数可以有三种状态,0-未出现过 1-出现奇数次 2-出现偶数次,那么以三进制进行状态压缩的话最多只有

3^10个状态,将每个数压缩成三进制进行dfs就可以很好的解决了。

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
using namespace std;
#define ll long long
const int maxm = 25;
ll dp[maxm][60006];
int d[maxm];
bool judge(int n)
{
	for (int i = 0;i <= 9;i++)
	{
		if (i % 2 == 0 && n % 3 == 2) return false;
		if (i % 2 == 1 && n % 3 == 1) return false;
		n /= 3;
	}
	return true;
}
int change(int s, int n)
{
	int a = s, b = n;
	while (b--) a /= 3;
	if (a % 3 < 2) s += pow(3.0, n);
	else s -= pow(3.0, n);
	return s;
}
ll dfs(int len, int num, int flag)
{
	if (len < 0) return judge(num);
	if (!flag&&dp[len][num] != -1) return dp[len][num];
	int k = flag ? d[len] : 9;
	ll ans = 0;
	for (int i = 0;i <= k;i++)
		ans += dfs(len - 1, num == 0 && i == 0 ? 0 : change(num, i), flag&&i == k);
	if (!flag) dp[len][num] = ans;
	return ans;
}
ll solve(ll n)
{
	int len = 0;
	while (n) d[len++] = n % 10, n /= 10;
	return dfs(len - 1, 0, 1);
}
int main()
{
	ll a, b, t;
	memset(dp, -1, sizeof(dp));
	scanf("%lld", &t);
	while (t--)
	{
		scanf("%lld%lld", &a, &b);
		printf("%lld\n", solve(b) - solve(a - 1));
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值