題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=3555
與HDU2089(不要62)相比,這道題是 “ 要49 ” ,比 “不要62” 的 dp[len][pre] 數組多了一個維度:dp[len][pre][exist]。
"不要62"不需要exist維度,只需要判斷到出現62的時候continue就可以了,“要49”需要exist維度,不需要在循環中判斷是否已經出現49,只要在參數傳遞的時候轉移一下就行。
#include <iostream>
#include <cstdio>
using namespace std;
typedef unsigned long long ull;
ull dp[25][10][2];
int digit[25];
ull dfs(int len, int pre, bool exist, bool limit){
if (len == 0){
return exist;
}
if (!limit && dp[len][pre][exist]){
return dp[len][pre][exist];
}
int Max = limit ? digit[len] : 9;
ull ans = 0;
for (int i=0; i<=Max; i++){
ans += dfs(len-1, i, exist||(pre==4 && i==9), limit&&(i==Max));
}
if (!limit){
dp[len][pre][exist] = ans;
}
return ans;
}
ull calc(ull n){
int len = 0;
while (n > 0){
digit[++len] = n % 10;
n /= 10;
}
return dfs(len, 0, false, true);
}
int main(){
int t;
ull n;
cin >> t;
while (t > 0){
t--;
scanf("%I64u", &n);
printf("%I64u\n", calc(n));
}
return 0;
}