SPOJ 10606. Balanced Numbers (数位DP,4级)

本文介绍使用数位DP技术解决寻找指定区间内平衡数的数量问题。平衡数定义为每个偶数位出现奇数次且每个奇数位出现偶数次的正整数。通过提供输入示例和详细代码解释,展示了如何通过数位DP方法来求解此类问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

10606. Balanced Numbers

Problem code: BALNUM

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

Added by:Angel Paredes
Date:2012-02-12
Time limit:1s
Source limit:50000B
Memory limit:256MB
Cluster:Pyramid (Intel Pentium III 733 MHz)
Languages:All except: PERL 6
Resource:Cuban Olympiad in Informatics 2012 - Day 2 Problem A









模板式数位DP。

#include<iostream>
#include<cstring>
#include<cstdio>
#define FOR(i,a,b) for(int i=a;i<=b;++i)
#define clr(f,z) memset(f,z,sizeof(f))
typedef long long LL;
using namespace std;
LL dp[20][60000];
int bit[20],num[20];
bool check(int x)
{
  int pos=0;
  while(x)
  {
    num[pos++]=x%3;
    x/=3;
  }
  FOR(i,0,pos-1)
  if(i%2==0&&num[i]==2)return 0;
  else if(i%2==1&&num[i]==1)return 0;
  return 1;
}
int turn(int s,int x)
{ int pos=0;
  clr(num,0);
  while(s)
  {
    num[pos++]=s%3;
    s/=3;
  }
  if(num[x]==0)++num[x];
  else num[x]=3-num[x];
  int z=max(x,pos-1);
  s=0;
  for(int i=z;i>=0;--i)
    {
      s=s*3+num[i];
    }
    return s;
}
LL DP(int pp,int s,bool nozero,bool big)
{
  if(pp==0)return check(s);
  if(big&&dp[pp][s]!=-1)return dp[pp][s];
  int kn=big?9:bit[pp];
  LL ret=0;
  FOR(i,0,kn)
  {
    ret+=DP(pp-1,(nozero||i!=0)?turn(s,i):0,nozero||i!=0,big||kn!=i);
  }
  if(big)dp[pp][s]=ret;
  return ret;
}
LL get(LL x)
{ int pos=0;

  while(x)
  {
    bit[++pos]=x%10;x/=10;
  }
  return DP(pos,0,0,0);
}
int main()
{
  LL a,b;
  int cas;clr(dp,-1);
  while(~scanf("%d",&cas))
  {
    while(cas--)
    {
      scanf("%lld%lld",&a,&b);
      printf("%lld\n",get(b)-get(a-1));
    }
  }
  return 0;
}


转载于:https://www.cnblogs.com/nealgavin/p/3797598.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值