题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3555
题目大意:1~n区间内不出现相邻的49的个数。
题目分析:数位DP。
代码参考:
#include<cstdio>
#include<cstring>
typedef long long LL;
const int N = 20;
LL dp[N][N];
int num[N];
//dp[i][0],表示存在49的个数
//dp[i][1],表示不存在49,但是最高位为9的个数
//dp[i][2],表示不存在49的个数
void init()//预处理
{
dp[0][2] = 1;
for(int i=1; i<20; ++i)//1 <= N <= 2^63-1,20位数以内
{
dp[i][0] = dp[i-1][0]*10 + dp[i-1][1];//在已经有49最高位加任意数字,或者在9之前加了4
dp[i][1] = dp[i-1][2];//就是在原先不含49的最高位加9
dp[i][2] = dp[i-1][2]*10 - dp[i-1][1];//在最高位加上任意数字,但是可能在9之前加了4
}
}
LL DP(LL n)//计算所有存在49的数字个数
{
int i, cnt = 0;
LL ans = 0, m = n;
bool f = false;
while(n)//分离出每一位上的数字
{
num[++cnt] = n%10;
n /= 10;
}
num[cnt+1] = 0;
for(i=cnt; i>0; --i)
{
ans += dp[i-1][0] * num[i];
if(f) ans += dp[i-1][2]*num[i];//高位已经出现49,后面的就随意
else if(num[i] > 4) ans += dp[i-1][1];//高位可能出现4的情况
if(num[i+1] == 4 && num[i] == 9) f = true;//高位已经出现4或者62
}
return ans;
}
int main()
{
init();
LL n;
int t;
scanf("%d", &t);
while(t--)
{
scanf("%I64d", &n);
printf("%I64d\n", DP(n+1));
}
return 0;
}