HDU - 3555

题意:数字中含有49的数字个数。

总结:dp[l][if4]表示当前还剩l位,上一位是否为4

判断时若上一位为4且这一位为9,不必再dfs,直接加上一个值就好

#include <bits/stdc++.h>

using namespace std;
const int maxn = 30 + 5;
#define ll long long

ll dight[maxn], dp[maxn][2], tot, T, z[maxn], n;

ll dfs(int l, bool if4, bool sig) {
	if(l == 0) return 0;
	if(!sig && dp[l][if4] != -1) return dp[l][if4];
	int nex = sig ?dight[l] :9; ll res = 0;
	for (int i = 0; i <= nex; ++i) {
		if(if4 && i == 9) res += sig ?n % z[l - 1] + 1 :z[l - 1];//加1是因为后面可以全为0 
		else res += dfs(l - 1, i == 4, sig && (i == nex));
	}
	if(!sig) dp[l][if4] = res;
	return res;
}
ll calc(ll a) {
	tot = 0;
	while(a) {
		dight[++tot] = a % 10; a /= 10;
	} 
	return dfs(tot, 0, 1);
}
int main() {
	scanf("%lld", &T); z[0] = 1;
	for (int i = 1; i <= 20; ++i) z[i] = z[i - 1] * 10;
	while(T--) {
		memset(dp, -1, sizeof dp);
		scanf("%lld", &n);
		printf("%lld\n", calc(n));
	}
	return 0;
}

  

 

猜你喜欢

转载自www.cnblogs.com/oi-forever/p/9126049.html