题目链接:https://vjudge.net/contest/396083#problem/D
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
翻译:
给定一个n,求1~n中有多少个符合条件的数
条件:这个数能被13整除,还包含13
分析:
如何判断这个数能被13整除,还包括13是重点
1.能被13整除?
对于每一位累加还原成原数的过程中直接取模
2.包括13?
k=0时:前i位没有13
k=1时:第i位位1
k=2时:前i位出现了13
随之而来的是三维数组:
dp[i][sta][k]:
完整代码:
#include<cstdio>
#include<cstring>
#include<math.h>
#include<stdlib.h>
#include<queue>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
LL n;
int a[30];
int dp[30][20][4];///dp[i][j][k]:前i位对13取模的结果是j,k=0前i位没有13,k=1前i位只有一个1,k=2前i位有13
LL dfs(int pos,int sta,int k,int limt)
{
if(pos==0)
return sta==0&&k==2;///保证余数为0,且出现过13
if(!limt&&dp[pos][sta][k]!=-1)
return dp[pos][sta][k];
int up=limt?a[pos]:9;
LL res=0;
for(int i=0; i<=up; i++)
{
int mod=(sta*10+i)%13;
if(k==1&&i==3||k==2)
res+=dfs(pos-1,mod,2,limt&&(i==up));
else if(i==1)
res+=dfs(pos-1,mod,1,limt&&(i==up));
else
res+=dfs(pos-1,mod,0,limt&&(i==up));
}
if(!limt)
dp[pos][sta][k]=res;
return res;
}
LL solve(LL x)
{
int tot=0;
while(x)
{
a[++tot]=x%10;
x/=10;
}
return dfs(tot,0,0,1);
}
int main()
{
memset(dp,-1,sizeof(dp));
while(~scanf("%lld",&n))
{
printf("%lld\n",solve(n));
}
return 0;
}