SPOJ - BALNUM Balanced Numbers

SPOJ - BALNUM

Balanced Numbers
Time Limit: 1000MS   Memory Limit: Unknown   64bit IO Format: %lld & %llu

[Submit]   [Go Back]   [Status]  

Description

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

Source

Cuban Olympiad in Informatics 2012 - Day 2 Problem A

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;

typedef long long ll;
int bit[111];;
ll dp[41][60003];
int news[60000][11];
bool ok[60003];
ll dfs(int pos,int s,bool e)
{
    if(pos==-1)return ok[s];
    if(!e&&~dp[pos][s])return dp[pos][s];
    int ed=e?bit[pos]:9;
    ll ans=0;
    for(int i=s?0:1;i<=ed;i++)
    {
        ans+=dfs(pos-1,news[s][i],e&&i==ed);
    }
    if(!e)dp[pos][s]=ans;
    return ans;
}
ll f(ll a)
{
    int len=0;
    while(a)
    {
        bit[len++]=a%10;
        a/=10;
    }
    ll res=0;
    for(int i=1;i<len;i++)
        res+=dfs(i-1,0,0);
    return res+=dfs(len-1,0,1);
}
bool ok1(int a[])
{
    for(int i=0;i<10;i++)
    {
        if(!a[i])continue;
        if(i&1)
        {
            if(a[i]&1)return 0;
        }else{
            if(~a[i]&1)return 0;
        }
    }
    return 1;
}
int main()
{   
    int T;cin>>T;
    memset(dp,-1,sizeof dp);
    memset(news,0,sizeof news);
    memset(ok,0,sizeof ok);
    for(int s=0;s<59049;s++)
    {
        int j=s;
        int exp[10];
        for(int i=0;i<10;i++,j/=3)
            exp[i]=j%3;
        if(s)ok[s]=ok1(exp);
        else ok[0]=0;
        for(int i=0;i<10;i++)
        {
            int t=exp[i];
            if(exp[i]&1)exp[i]=2;
            else exp[i]=1;
            for(int j=9;j>=0;--j,news[s][i]*=3)
                news[s][i]+=exp[j];
            news[s][i]/=3;
            exp[i]=t;
        }
    }
    ///cout<<news[0][3];
    while(T--)
    {
        ll  a,b;
        cin>>a>>b;
        cout<<f(b)-f(a-1)<<endl;
    }
}




你可能感兴趣的:(Algorithm,DFS)