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.
13 100 200 1000
1 1 2 2
【题解】
这道题很像那道 不要62 题的翻版,不过难度高一点,这几天一直写数位dp,基本都是三维的,所以思维也一直局限在三维的环境中,在这道题上一直解不出来,最后突发奇想,多加一个状态,立马就简单多了。
题意就是要你找从1到n区间内的含13且是13倍数的数的个数。
含13这个好说,不要62 那道题就有,直接标记前一位是不是为1,再判断当前位是不是3就好,但是麻烦的是要能被13整除,这意味着每次都要保存前几位组成的数值,在下一次的时候乘10加i,但是这样数据很大,数组会爆,怎么办呢?
这就要用到一点数学知识了,一个数直接取mod 和从高位按位取mod 最后的结果是一样的,这样就简单多了,每次只保存前面数mod13后的结果就好,数组空间一下小了很多。
然后就是分情况讨论了,按照有没有13分,有的话往后就只需要考虑能不能mod13就行了,没有的话就好同时记录13和mod13,其他的就和模板一样了。
具体看代码注释吧。
【AC代码】
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef __int64 ll; //备用的 结果没用到
int dp[12][2][20][2];//位数 前一位是否为1 %13的值 是否已经有13
int m,n;
int num[12];
int dfs(int pos,bool pre_is1,int mod,bool is_13,bool limit)//前四位与定义一样 最后一位是上限
{
if(pos<0) return is_13&&mod==0;//注意同时满足含13和mod等于0
if(!limit && dp[pos][pre_is1][mod][is_13]!=-1) return dp[pos][pre_is1][mod][is_13];//往下都是数位dp套路
int ans=0;
int endi= limit ? num[pos] : 9 ;
for(int i=0;i<=endi;++i)
{
int next_mod=mod*10+i; //稍微算一下就知道 一个数直接mod x的结果和从高位依次按位mod x的结果是一样的 这样可以降低空间消耗
if(!is_13)//如果还没有出现含13的就需要特殊处理
{
if(pre_is1&& i==3) ans+=dfs(pos-1,0,next_mod%13,true,limit&&i==endi);//如果上一位和当前位就能组成13
else ans+=dfs(pos-1,i==1,next_mod%13,0,limit&&i==endi); //不能组成的话就继续寻找
}
else//已经有13了
{
ans+=dfs(pos-1,i==1,next_mod%13,true,limit&&i==endi);//只考虑能不能除尽就好
}
}
if(!limit) dp[pos][pre_is1][mod][is_13]=ans;
return ans;
}
int solve(int x)
{
int len=0;
while(x)
{
num[len++]=x%10;
x/=10;
}
return dfs(len-1,0,0,0,1);
}
int main()
{
memset(dp,-1,sizeof(dp));
while(~scanf("%d",&m))
{
printf("%d\n",solve(m));
}
return 0;
}