上題目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));
}
}