问题描述:
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
大致题意:
给出一个区间,找出含有13并且能被13整除的数。
思路分析:
前一位与后一位并没有明显的关系。
这个题要找出,能被13整除的,能不能被13整除是一个整体的性质,在我们不知道确切数的时候想要得到余数,就要用到上一个状态的余数。再配合DFS得到结果。
ac代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int bit[15];
int dp[15][15][3];
int dfs(int pos,int mod,int have,int lim)//lim记录上限
{
int num,i,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];
num = lim?bit[pos]:9;//假设该位是2,下一位是3,如果现在算到该位为1,那么下一位是能取到9的,如果该位为2,下一位只能取到3
ans = 0;
for(i = 0; i<=num; i++)
{
mod_x = (mod*10+i)%13;//看是否能整除13,而且由于是从原来数字最高位开始算,细心的同学可以发现,事实上这个过程就是一个除法过程
have_x = have;
if(have == 0 && i == 1)//末尾不是1,现在加入的是1
have_x = 1;//标记为末尾是1
if(have == 1 && i != 1)//末尾是1,现在加入的不是1
have_x = 0;//标记为末尾不是1
if(have == 1 && i == 3)//末尾是1,现在加入的是3
have_x = 2;//标记为含有13
ans+=dfs(pos-1,mod_x,have_x,lim&&i==num);
}
if(!lim)
dp[pos][mod][have] = ans;//扫描记忆化搜索
return ans;
}
int main()
{
int n,len;
while(~scanf("%d",&n))
{
memset(bit,0,sizeof(bit));
memset(dp,-1,sizeof(dp));
len = 0;
while(n)
{
bit[++len] = n%10;
n/=10;
}
printf("%d\n",dfs(len,0,0,1));
}
}