【動態規劃】【數位DP】[SPOJ10606]Balanced numbers

題目描述

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

樣例輸入

2
1 1000
1 9

樣例輸出

147
4

題目分析

在這裏我推薦使用遞歸版本+記憶化的方法來做本題目方便些
首先我們看到本題目可以使用

f(i,S,k)
來表示一個狀態其中i 表示當前已經枚舉到了第i 位,k 表示當前是否需要嚴格小於(0爲不需要,1爲需要),S爲一個3進制的10位數,每一位表示對應的數字出現的奇(1)偶(2)性,同時0表示沒有出現過,那麼我們對於當前枚舉到的數字m 我們可以將其加入,很容易可以發現遞推式,其中我們另當前的數範圍轉換成字符串其中第i 位表示爲Ai 該數字一共有n
f(i,j,k)=Ai1p=0f(i+1,g(j,p),0)+f(i+1,g(j,Ai),1)9p=0f(i+1,g(j,p),0)1(k=1)(k1)(i>n)(check(j)==1)
其中check爲檢查j中的狀態是否爲奇數位上爲2或者0,偶數位上是否爲1或0
同時有
g(i,j)={i3ji+3j(i/3j%3==2)(i/3j%3==1||2)
那麼我們可以通過遞歸求得最終的答案就是
cal(R)cal(L1)cal(i)=f(1,0,1)
其中的cal(i) 中的是針對if 那麼

代碼

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXS = 19683*3;
const int MAXN = 20;
long long _pow[11]={1,3,9,27,81,243,729,2187,6561,19683}, f[MAXN+2][MAXS+10][2];
int _handle(int s, int u){
    if(!s && !u) return 0;
    if(s/_pow[u]%3 <= 1) s+=_pow[u];
    else s-=_pow[u];
    return s;
}
char s[MAXN+10];
int Len;
long long dp(int u, int S, int k){
    if(~f[u][S][k]) return f[u][S][k];
    f[u][S][k] = 0;
    if(u == 0){
        for(int i=0;i<=9;i++){
            if(i%2==0&&S/_pow[i]%3==2) return f[u][S][k] = 0;
            else if(i%2!=0&&S/_pow[i]%3==1) return f[u][S][k] = 0;
        }
        return f[u][S][k] = 1;
    }
    int up = k != 0 ? s[u]-'0' : 9;
    for(int i=0;i<=up;i++){
        if(k > 0 && i == up) f[u][S][k] += dp(u-1, _handle(S, i), 1);
        else f[u][S][k] += dp(u-1, _handle(S, i), 0);
    }
    return f[u][S][k];
}
long long solve(long long u){
    memset(f, -1, sizeof f);
    Len = 0;
    while(u){s[++Len]=u%10+'0', u/=10;}
    return dp(Len, 0, 1);
}
int main(){
    long long a, b;
    int t;
    scanf("%d", &t);
    while(t--){
        cin>>a>>b;
        cout<<solve(b)-solve(a-1)<<endl;
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章