Bomb HDU - 3555
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
The first line of input consists of an integer T (1 <= T <= 10000), indicating the number of test cases. For each test case, there will be an integer N (1 <= N <= 2^63-1) as the description.
The input terminates by end of file marker.
Output
For each test case, output an integer indicating the final points of the power.
Sample Input
3
1
50
500
Sample Output
0
1
15
Hint
From 1 to 500, the numbers that include the sub-sequence “49” are “49”,“149”,“249”,“349”,“449”,“490”,“491”,“492”,“493”,“494”,“495”,“496”,“497”,“498”,“499”,
so the answer is 15.
题目大意:
已知所有含有49的数字是不合法的,问nnn以内有多少不合法的数字。
解题思路:
假设dp[i][j]dp[i][j]dp[i][j]代表第iii以下所有合法的数字的数目,jjj代表当前位是否是4.
因此,我们可以先将数字按位拆分放在数组中,从最高位开始,我们可以知道,如果当前位不为4,那么此时的dp[i][0]dp[i][0]dp[i][0]就会等于其下一位的所有情况的累加,而这种累加我们将其存在dp[i−1][0]dp[i-1][0]dp[i−1][0]与dp[i−1][1]dp[i-1][1]dp[i−1][1]中,只要算过一次,当下一次遇到时就可直接调用,大大降低了重复计算次数,当当前为为4时,将其存入dp[i][1]dp[i][1]dp[i][1]中,遍历下一位时仅需跳过9即可,其他情况相同。
代码:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <set>
#include <utility>
#include <sstream>
#include <iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define inf 0x3f3f3f3f
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define lep(i,l,r) for(int i=l;i>=r;i--)
#define ms(arr) memset(arr,0,sizeof(arr))
//priority_queue<int,vector<int> ,greater<int> >q;
const int maxn = (int)1e5 + 5;
const ll mod = 1e9+7;
ll dp[25][2];
ll num[25];
int cnt;
ll dfs(int wei,bool limit,bool is4) {if(wei==0) return 1;if(!limit&&dp[wei][is4]) return dp[wei][is4];int maxnum;if(limit) maxnum=num[wei];else maxnum=9;ll nape=0;for(int i=0;i<=maxnum;i++) {if(is4&&i==9) continue;nape+=dfs(wei-1,limit&&i==maxnum,i==4);}if(!limit) dp[wei][is4]=nape;return nape;
}
int main()
{#ifndef ONLINE_JUDGE//freopen("in.txt", "r", stdin);#endif//freopen("out.txt", "w", stdout);//ios::sync_with_stdio(0),cin.tie(0);int T;scanf("%d",&T);while(T--) {ll n,n1;cnt=0;scanf("%lld",&n);n1=n;while(n) {num[++cnt]=n%10;n=n/10;}printf("%lld\n",n1+1-dfs(cnt,true,false));}return 0;
}