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

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;
}


你可能感兴趣的:(SPOJ 10606. Balanced Numbers (数位DP,4级))