B-number HDU - 3652
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
大致题意
找出1~n范围内含有13并且能被13整除的数字的个数
思路:使用记忆化深搜来记录状态,配合数位DP来解决
代码如下
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<string>
#include<queue>
using namespace std;
int bit[15];
int dp[15][15][3];
//dp[i][j][k]
//i:数位
//j:余数
//k:3种操作状况,0:末尾不是1,1:末尾是1,2:含有13
int dfs(int pos,int mod,int have,int lim)// pos:当前的位数 mod:当前余数 have:表示末尾数是否为1 lim:记录上限
{
int num,i,ans,mod_x,have_x;
if(pos<=0)
return mod==0&&have==2;//如果已经到了最后一个位数,判断此时余数是否为0(即判断该数是否可以被13整除),判断是否含有13
if(!lim&&dp[pos][mod][have]!=-1)//没有上限且已经被访问过
return dp[pos][mod][have];
num=lim?bit[pos]:9;// 如果前面已经达到上限,则现在能选取的数最大为bit[pos],否则为9
ans=0;
for(int 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);//lim&&i==num,在最开始,取出的num是最高位,所以如果i比num小,那么i的下一位都可以到达9,而i==num了,最大能到达的就只有,bit[pos-1]
}
if(!lim)
dp[pos][mod][have]=ans;
return ans;
}
int main()
{
int n,len;
while(cin>>n)
{
memset(bit,0,sizeof(bit));
memset(dp,-1,sizeof(dp));
len=0;
while(n)
{
bit[++len]=n%10;
n/=10;
}
cout<<dfs(len,0,0,1)<<endl;
}
return 0;
}
原址:http://blog.youkuaiyun.com/qq_33583069/article/details/51842294