AtCoder Beginner Contest 007 D - 禁止された数字

原题链接:D - 禁止された数字

题目大意:给二个数字n和m,m>n,求从n到m的所有数字中含4和9的数字个数。

思路:数据非常的大,肯定不能直接从n到m枚举每个数,那么这种情况下可以想到数位dp。可以用数位dp求不包含4和9的数字,然后用总数减去不包含的数字就是答案。

#pragma GCC optimize(2)
#include
#define endl '\n' 
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair pii;
const int N=1e6+10,mod=10007;
ll cnt=0,p[N];
ll f[100];
ll dfs(ll len,bool limit)
{
	if(len==-1)return 1;
	if(!limit&&f[len])return f[len];
	ll up=limit?p[len]:9;
	ll sum=0;
	for(int i=0;i<=up;i++)
	{
		if(i==4||i==9)continue;
		sum=sum+dfs(len-1,i==p[len]&&limit);
	}
	if(!limit)f[len]=sum;
	return sum;
}
ll solve(ll x)
{
	cnt=0;
	while(x)
	{
		p[cnt++]=x%10;
		x/=10;
	}
	return dfs(cnt-1,1);
}
int main()
{
    ios::sync_with_stdio(NULL);
	cin.tie(0),cout.tie(0);
	ll n,m;cin>>n>>m;
	cout<<(m-solve(m))-(n-1-solve(n-1))<

你可能感兴趣的:(算法,c++,数据结构)