B-number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5957 Accepted Submission(s): 3435
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
|
#include <bits/stdc++.h>
#define mst(a) memset(a,-1,sizeof(a))
#define f(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
int bit[12];
int dp[12][15][3];
//0:没有13且最后一位不为1,1:没有13且最后一位为1,2:有13
//flag=1;无限制,flag=0,有限制
int dfs(int pos,int mod,int st,int flag)
{
if(pos==0) return mod==0&&st==2;
if(flag&&dp[pos][mod][st]!=-1) return dp[pos][mod][st];
int sum=0;
int x=flag?9:bit[pos];
f(i,0,x)
{
int mod_x=(mod*10+i)%13;
if((st==2)||(st==1&&i==3))
sum+=dfs(pos-1,mod_x,2,flag||i<x);
else if(i==1) sum+=dfs(pos-1,mod_x,1,flag||i<x);
else sum+=dfs(pos-1,mod_x,0,flag||i<x);
}
if(flag) dp[pos][mod][st]=sum;
return sum;
}
int cal(int x)
{
int len=0;
while(x)
{
bit[++len]=x%10;
x/=10;
}
return dfs(len,0,0,0);
}
int main()
{
int n;
mst(dp);
while(~scanf("%d",&n))
{
printf("%d\n",cal(n));
}
return 0;
}