求1-n之间含有13且能被13整除的数的个数。
记忆化搜索+数位dp.
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<iomanip>
#include<map>
#include<algorithm>
#include<queue>
#include<set>
#define inf 10000000
#define pi acos(-1.0)
#define eps 1e-8
#define seed 131
using namespace std;
typedef pair<int,int> pii;
typedef unsigned long long ULL;
typedef long long LL;
const int maxn=100005;
int dp[15][15][3][2];
//0:不含13,末尾不为1;
//1:不含13,末尾为1;
//2:含13;
int n;
int digit[15];
int dfs(int pos,int mod,int have,int lim)//分别对应四维的含义
{
if(pos==0)
return (mod==0&&have==2);
if(dp[pos][mod][have][lim]!=-1)
return dp[pos][mod][have][lim];
int num=lim?digit[pos]:9;
int ans=0;
for(int i=0;i<=num;i++)
{
if(have==0)
{
if(i==1)
ans+=dfs(pos-1,(mod*10+i)%13,1,lim&&(i==num));
else
ans+=dfs(pos-1,(mod*10+i)%13,0,lim&&(i==num));
}
else if(have==1)
{
if(i==3)
ans+=dfs(pos-1,(mod*10+i)%13,2,lim&&(i==num));
else if(i==1)
ans+=dfs(pos-1,(mod*10+i)%13,1,lim&&(i==num));
else
ans+=dfs(pos-1,(mod*10+i)%13,0,lim&&(i==num));
}
else
ans+=dfs(pos-1,(mod*10+i)%13,2,lim&&(i==num));
}
dp[pos][mod][have][lim]=ans;
return ans;
}
int main()
{
while(~scanf("%d",&n))
{
memset(dp,-1,sizeof(dp));
int cnt;
for(cnt=1;;cnt++)
{
digit[cnt]=n%10;
n/=10;
if(n==0)
break;
}
printf("%d\n",dfs(cnt,0,0,1));
}
return 0;
}