题目:http://acm.hdu.edu.cn/showproblem.php?pid=2089
题意:给出一个区间L,R,问在L,R中有多少个不含62和4的数。
思路:数位DP,DP[pos][pre]表示上一位是否是6(pre是否为1)时,后pos位满足条件的数的个数。细节见代码注释。
附上一份大佬写的很好的数位DP教程模板:http://blog.csdn.net/wust_zzwh/article/details/52100392
代码:
#include
#include
#include
#define met(s,k) memset(s,k,sizeof s)
#define scan(a) scanf("%d",&a)
#define scanl(a) scanf("%lld",&a)
#define scann(a,b) scanf("%d%d",&a,&b)
#define scannl(a,b) scanf("%lld%lld",&a,&b)
#define scannn(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define prin(a) printf("%d\n",a
#define prinl(a) printf("%lld\n",a)
using namespace std;
typedef long long ll;
ll n,m;
int num[20];
ll dp[20][2];
ll dfs(int pos,int pre,int limt)
{
ll cont=0;//记录满足条件的数的个数
if(pos==-1)return 1;//当枚举到-1位时,说明已枚举完,并且这个数合法,返回1
if(!limt&&dp[pos][pre]!=-1)return dp[pos][pre];//当当前位没有限制时,后面pos-1位可以取0~9的任意数,满足条件的数为dp[pos][pre]
int up=limt?num[pos]:9;//判断枚举上线
for(int i=0;i<=up;i++)
{
if((pre&&i==2)||i==4)continue;//不合法的枚举
cont+=dfs(pos-1,i==6,limt&&i==up);
}
if(!limt)dp[pos][pre]=cont;//记录状态
return cont;
}
ll solve(ll x)
{
int pos=0;
while(x)
{
num[pos++]=x%10;
x/=10;
}
return dfs(pos-1,0,1);
}
int main()
{
met(dp,-1);
while(scannl(n,m),m)
{
prinl(solve(m)-solve(n-1));
}
return 0;
}