hdu3652 B-number(数位dp+dfs)

B-number

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3376 Accepted Submission(s): 1891


Problem Description
A wqb-number, or B-number for short, is a non-negative integer whose decimal form contains the sub- string "13" and can be divided by 13. For example, 130 and 2613 are wqb-numbers, but 143 and 2639 are not. Your task is to calculate how many wqb-numbers from 1 to n for a given integer n.

Input
Process till EOF. In each line, there is one positive integer n(1 <= n <= 1000000000).

Output
Print each answer in a single line.

Sample Input

13 100 200 1000

Sample Output

1 1 2 2

Author
wqb0039

Source
2010 Asia Regional Chengdu Site —— Online Contest 

题意:找出1~n有多少个数既含有13又能被13整除。
分析:记忆化搜索配合数位dp求解。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
const double eps = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
#define ll long long
#define CL(a) memset(a,0,sizeof(a))

int dp[15][15][3],s[15];//dp[i][j][k],i表示位数,j表示余数,k表示末尾是1、末尾不是1、含有13.

int dfs(int pos, int mod, int have, int lim)//前三个数对应数组dp,lim表示上限
{
    int num,ans,mod_x,have_x;
    if (pos <= 0)
        return mod==0&&have==2;
    if (!lim && dp[pos][mod][have]!=-1) //没有上限且被访问过
        return dp[pos][mod][have];
    ans = 0;
    num = lim?s[pos]:9;//如果有上限,只能取到当前位数,如果没上限,可取到9
                        //假设该位是2,下一位是3,如果现在算到该位为1,那么下一位是能取到9的,如果该位为2,下一位只能取到3
    for (int i=0; i<=num; i++)
    {
        mod_x = (mod*10+i)%13;//该位的每种情况对13取模
        have_x = have;
        if (have==0 && i==1)//末尾加1
            have_x=1;
        if (have==1 && i!=1)//末尾已经为1了
            have_x=0;
        if (have==1 && i==3)//末尾是1,现在加3
            have_x=2;
        ans+=dfs(pos-1, mod_x, have_x, lim&&i==num);//如果i==num,下一位能取的最大数就为s[pos-1],i!=num,下一位能取到9
    }
    if (!lim)
        dp[pos][mod][have] = ans;
    return ans;
}

int main ()
{
    int n,t;
    while (scanf ("%d",&n)==1)
    {
        CL(s);
        memset(dp, -1, sizeof(dp));
        t = 0;
        while (n)
        {
            s[++t]=n%10;
            n/=10;
        }
        cout<


你可能感兴趣的:(ACM—dp,各OJ刷题专栏)