【hdu3555】【数位DP】Bomb

较裸的数位DP,不过也是我的第一道数位DP,使用记忆化的方法实现比较简洁。

代码:

#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 20;
int dig[maxn];
long long dp[maxn][maxn][2];
long long n;
void init()
{
	freopen("hdu3555.in","r",stdin);
	freopen("hdu3555.out","w",stdout);
}

long long F(int pos,int last,bool have,bool inf)
{
	long long ans = 0;
	if(pos == -1)return have;
	if(!inf && dp[pos][last][have] != -1)return dp[pos][last][have];
	int end = inf ? dig[pos] : 9;
	for(int i = 0;i <= end;i++)
	{
		if(last == 4 && i == 9)ans += F(pos - 1,i,true,inf && (i == end));
		else ans += F(pos - 1,i,have,inf && (i == end));
	}
	if(!inf)dp[pos][last][have] = ans;
	return ans;
}

long long calc(long long t)
{
	int pos = 0;
	while(t)
	{
		dig[pos++] = t % 10;
		t /= 10;
	}
	return F(pos - 1,0,0,1);
}

void readdata()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		memset(dp,-1,sizeof(dp));
		scanf("%lld",&n);
		printf("%lld\n",calc(n));
	}
}

int main()
{
	init();
	readdata();
	return 0;
}


你可能感兴趣的:(【hdu3555】【数位DP】Bomb)