hdu 3652 B-number
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3652
题意:
给出一个数N,求1-N中有多少个数,其中出现了13且能被13整除。
思路:数位DP,记忆化搜索判断是否同时满足两个条件。
1 #include <bits/stdc++.h> 2 using namespace std; 3 int num[15]; 4 int n; 5 int dp[15][15][2][2]; 6 int dfs(int cur, int last, int state, int mark, int limit) 7 { 8 if(cur < 0) 9 { 10 if(mark == 1 && last == 0) return 1; 11 else return 0; 12 } 13 if(!limit && dp[cur][last][state][mark] != -1) return dp[cur][last][state][mark]; 14 15 int up = limit?num[cur]:9; 16 int ret = 0; 17 for(int i = 0; i <= up; i++) 18 { 19 int temp = (last*10+i)%13; 20 int nowmark; 21 22 if(mark == 1) nowmark = 1; 23 else if(mark == 0 && state == 1 && i == 3) nowmark = 1; 24 else nowmark = 0; 25 26 ret += dfs(cur-1, temp, i == 1, nowmark, limit && i == up); 27 } 28 if(!limit) dp[cur][last][state][mark] = ret; 29 return ret; 30 } 31 int slove(int x) 32 { 33 memset(dp, -1, sizeof(dp)); 34 int cnt = 0; 35 while(x) 36 { 37 num[cnt++] = x%10; 38 x /= 10; 39 } 40 return dfs(cnt-1, 0, 0, 0, 1); 41 } 42 int main() 43 { 44 // freopen("in.txt", "r", stdin); 45 // freopen("out.txt", "w", stdout); 46 while(~scanf("%d", &n)) 47 { 48 printf("%d\n", slove(n)); 49 } 50 return 0; 51 }