hdu 3652 B-number(數位dp)
http://acm.hdu.edu.cn/showproblem.php?pid=3652
大致題意:"B-number"即一個整數含有子串"13"且被13整除。求1-n之間這樣的數的個數。
思路:有兩個限制條件:含有子串“13”和能被13整除。那麼設dp[site][mod][flag],表示到第site位對13取餘為mod且標記為flag的數的個數。flag表示是否含有子串"13"。然後進行記憶話搜尋。
#include <stdio.h>#include <iostream>#include <map>#include <stack>#include <vector>#include <math.h>#include <string.h>#include <queue>#include <string>#include <stdlib.h>#include <algorithm>#define LL long long#define _LL __int64#define eps 1e-8#define PI acos(-1.0)using namespace std;int dp[15][15][5];int dig[15];//flag = 0表示前一個不是1,flag = 1表示前一個是1,flag = 2表示出現"13"。int dfs(int site, int mod, int flag, int up){ if(site == 0) return mod == 0 && flag == 2; //當mod為0且有"13"時,返回1 if(!up && dp[site][mod][flag] != -1)//記憶化 return dp[site][mod][flag]; int len = up ? dig[site] : 9; int ans = 0; for(int i = 0; i <= len; i++) { int tmod = (mod*10 + i) % 13; int tflag = flag; if(flag == 1 && i == 3) tflag = 2; else if(flag == 0 && i == 1) tflag = 1; else if(flag == 1 && i != 1) tflag = 0; ans += dfs(site-1, tmod, tflag, up && (i == len) ); } if(!up) dp[site][mod][flag] = ans; return ans;}int cal(int n){ int cnt = 0; while(n) { dig[++cnt] = n % 10; n /= 10; } memset(dp,-1,sizeof(dp)); return dfs(cnt,0,0,1);}int main(){ int n; while(~scanf("%d",&n)) { printf("%d\n",cal(n)); } return 0;}