题目大意:给定区间[L,R],求在区间内有多少个包含"13"又被13整除的数。
基础的一道数位DP,我们不妨设dp[pos][mod][sta]表示从高位填数至第pos位,除13余数为mod,含有13的状态为sta(1表示上一个数是1,2表示包含 13,0表示没有包含13)的方案数,照这个状态进行记忆化搜索即可。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define MAXLEN 10
#define MAXNUM 9
#define MAXMOD 13
#define INF 0x3f3f3f3f
typedef long long int LL;
int dp[MAXLEN+10][MAXMOD+10][3];
int Num[MAXLEN+10];
int Len;
void GetNum(int x)
{
memset(Num,0,sizeof(Num));
Len=0;
while(x)
{
Num[++Len]=x%10;
x/=10;
}
return;
}
int dfs(int len,int mod,int flag,bool lim)
{
if(len<=0)
{
if(mod==0&&flag==2)
return 1;
else return 0;
}
if(!lim&&dp[len][mod][flag]!=-1)
return dp[len][mod][flag];
int Nmax,i,rn,mod_x,flag_x;
int ans=0;
Nmax=lim?Num[len]:9;
for(i=0;i<=Nmax;++i)
{
mod_x=(mod*10+i)%13;
flag_x=flag;
if(flag==0&&i==1)
flag_x=1;
else if(flag==1&&i==3)
flag_x=2;
else if(flag==1&&i!=1)
flag_x=0;
ans+=dfs(len-1,mod_x,flag_x,lim&&i==Nmax);
}
if(!lim)
dp[len][mod][flag]=ans;
return ans;
}
int main()
{
int N;
while(~scanf("%d",&N))
{
memset(dp,-1,sizeof(dp));
GetNum(N);
printf("%d\n",dfs(Len,0,0,1));
}
}