【题解】Bomb

来源:互联网 发布:蜀地割据知乎 编辑:程序博客网 时间:2024/05/17 01:32

Bomb

Description

    反恐怖主义分子在尘土中发现了一枚计时炸弹。 但是这次恐怖分子改进了定时炸弹。 计时炸弹的数字序列从1到N.如果当前数字序列包含子序列“49”,爆炸的力量将增加一点。

    现在反恐怖主义分子知道数字N, 他们想要知道威力的最终点。 你能帮助他们吗?

(原文:The counter-terrorists found a time bomb in the dust. But this time the terrorists improve on the time bomb. The number sequence of the time bomb counts from 1 to N. If the current number sequence includes the sub-sequence "49", the power of the blast would add one point.
Now the counter-terrorist knows the number N. They want to know the final points of the power. Can you help them?)


Input

    第一行输入由整数T(1 <= T <= 10000)组成,表示测试用例数。 对于每个测试用例,将会有一个整数N(1 <= N <= 2 ^ 63-1)作为描述。输入以文件标记的末尾终止。


Output

    对于每个测试用例,输出指示功率的最终点的整数。


Sample Input

3

1

50

500


Sample Output

0

1

15


就是一道数位dp的题。

对于数位dp的题目,搜索大法:将一个数拆成一位一位来搜索,注意是记忆化搜索。

对于dfs(len,last_4,full),

len代表搜索到第几位,

last_4代表上一位是不是4,

full代表上一位是否等于num[len+1]。

注意题目给出的数据范围要使用long long。

代码:

#include <cstdio>long long f[23][2];int num[23];long long dfs(int len,bool last_4,bool full){if(!len)return 1;if(!full && f[len][last_4])return f[len][last_4];long long sum=0;for(int i=0;i<=(full?num[len]:9);++i)if(!(last_4&&i==9))sum+=dfs(len-1,i==4,full&&i==num[len]);if(!full)f[len][last_4]=sum;return sum;}long long getans(long long n){num[0]=0;while(n!=0){num[++num[0]]=n%10;n/=10;}return dfs(num[0],false,true);}int main(){long long n;int t;scanf("%d",&t);for(int i=1;i<=t;++i)scanf("%lld",&n),printf("%lld\n",n-getans(n)+1);}

原创粉丝点击