上题目B-number
题目描述
B-number
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
解析
思路是记忆化搜索。
//设dp[pos][mod][t][now]
//pos:正在处理的数位,mod:模13的余数,t:是否包含13,now:结尾的数字(因为记忆化搜索从高位到低位)
#include<bits/stdc++.h>
using namespace std;
int dp[10][15][2][10],bit[10],len,n;
int dfs(int pos,int mod,bool t,int now,bool flag)//flag:是否有取值限制
{
if(!pos)return mod==0&&t;//搜索完所有数位则返回
if(!flag&&dp[pos][mod][t][now]!=-1)return dp[pos][mod][t][now];
//搜索过且无取值限制则返回搜索过的值
int end=flag?bit[pos]:9,ans=0;//三目运算:如果无取值限制,则范围取最大9;如果有取值限制,则范围取上一位
for(int i=0;i<=end;i++)//继续搜索下一位
ans+=dfs(pos-1,(mod*10+i)%13,t||(now==1&&i==3),i,flag&&(i==end));
if(!flag)dp[pos][mod][t][now]=ans;//若无取值限制才赋值
return ans;
}
int solve(long long n)
{
while(n)
{
bit[++len]=n%10;
n/=10;
}
return dfs(len,0,0,0,1);//从最高位开始搜索,有取值限制
}
int main()
{
memset(dp,-1,sizeof(dp));
while(~scanf("%d",&n))
{
len=0;
printf("%d\n",solve(n));
}
}