1382: 简单题2
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 55 Solved: 22
[ Submit][ Status][ Web Board]
Description
New 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.
【解析】
这道题的话其实是经典的数位dp的题,我们要枚举所有的可能。题目的大致意思就是在1-n这个序列当中寻找数字包含49这个子序列的数字一共有多
少个。dp[i][0]代表长度为 i 并且不含有49的数字的个数;dp[i][1]代表长度为 i 并且不含有49,但是最高位是9的数字的个数;dp[i][2]代表长
度为 i 并且含有49的数字的个数。
dp[i][0] = dp[i-1][0] * a[i] - dp[i-1][1]; 表示长度为 i 的不含有49的数字的个数等于长度为 i - 1 的不含有49的数字的个数*当前的数字,因为这个位置可以填0~a[i] - 1,减去d[i-1][1]是因为dp[i-1][1]表示的是第i-1位的最高位是9如果在最高位加上了4那就不行了,所以要减去。
dp[i][1] = dp[i-1][0]; 表示长度为 i 的并且不含有49同时最高位是9的数字的个数等于,长度为 i - 1 的不含有49的数字的个数,因为只要在它的高一位加上一个9就可以了。
dp[i][2] = dp[i-1][2] * a[i] + dp[i-1][1]; 表示长度为 i 的含有49的数字的个数等于,长度为 i - 1 的数字的个数*当前的数字,再加上长度为 i - 1 的并且
不含有49同时最高位是9的数字的个数,因为这个时候,只要在高一位加上一个4就可以了,这样在最高的两位就组成了一个49。
从数字的高位向低位扫描,对于第 i 位,首先加上长度为 i - 1 的符合条件的数字个数;
再讨论以前是不是出现过49,如果出现过,就要再追加上长度为 i - 1 的不符合条件的数字的个数,因为以前已经有49了;所以后面几位当中未
出现过9的数字要加上去,比如说一个数是4957,放到数组里面逆着存储就变成了7594,这样的话比如判断的位数到了5那里,肯定要加上那57个数
所以这也是个判断条件 如果没有出现过,就要判断这一位是不是大于4呢,如果大于4,就要再追加上长度为 i - 1 的不含有49但是最高位是9的数字的个数,因为这个时 候可以再这一位填4,因为它是大于4的; 然后就是判断一下,当前位和上一位是不是满足49,如果满足,标记出现了49了!为以后的判断做准备。#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; long long dp[25][3]; void facs() { memset(dp,0,sizeof(dp)); dp[0][0] = 1; int i; for(i = 1;i<=22;i++) { dp[i][0] = dp[i-1][0]*10-dp[i-1][1];//长度为i但不含有49 dp[i][1] = dp[i-1][0];//长度为i最高位位9的 dp[i][2] = dp[i-1][2]*10+dp[i-1][1];//长度为i包含49的 } } long long solve(long long n) { long long i,tem = n,len = 0,a[25],flag = 0,ans = 0; while(n) { a[++len] = n%10; n/=10; } a[len+1] = 0; for(i = len;i;i--) { ans+=dp[i-1][2]*a[i]; if(flag) ans+=dp[i-1][0]*a[i]; if(!flag && a[i]>4)//可以在最高位插一个4进去 ans+=dp[i-1][1]; if(a[i+1] == 4 && a[i] == 9) flag = 1; } return ans; } int main() { int t; long long n; scanf("%d",&t); facs(); while(t--) { scanf("%lld",&n); printf("%lld\n",solve(n+1)); } return 0; }