与13有关(数位dp)

找出1~n范围内含有13并且能被13整除的数字的个数.

#include 
#include 
#include 
#include  
using namespace std;

int n, shu[20], dp[20][20][10]; 
int dfs(int len, int mod, int state, bool shangxian)
{
    if (len == 0)
        return mod == 0 && state == 2;
    if (!shangxian && dp[len][mod][state])
        return dp[len][mod][state];
    int cnt = 0, maxx = (shangxian ? shu[len] : 9);
    for (int i = 0; i <= maxx; i++)
    {
        int tz = state;
        if (state != 2 && i != 1)//不进行记录
            tz = 0;
		if (state != 2&& i == 1 )//标记当前位是1
            tz = 1;
        if (state== 1 && i == 3)//出现13,标记state=2,只要寻找出后面的数字组合;
            tz = 2; 
        cnt += dfs(len - 1, (mod * 10 + i) % 13, tz, shangxian && i == maxx);
    }
    if (!shangxian)
        dp[len][mod][state] = cnt;
    return cnt;
}

int main()
{
    while (~scanf("%d", &n))
    {
        memset(shu, 0, sizeof(shu));
        memset(dp, 0, sizeof(dp));
        int k = 0;
        while (n)
        {
            shu[++k] = n % 10;
            n /= 10;
        }
        printf("%d\n", dfs(k, 0, 0, 1));
    } 
    return 0;
}

你可能感兴趣的:(动态规划)