首页 > ACM题库 > HDU-杭电 > hdu 3555-bomb-动态规划-[解题报告]hoj
2014
11-05

hdu 3555-bomb-动态规划-[解题报告]hoj

Bomb

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 7487    Accepted Submission(s): 2610

Problem Description
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.
 
 
题意:给出n,求出[1,n]中多少个数包含49;
思路:数位dp。

1.dp[len][0] 代表数字长度为len不含49的个数 

2.dp[len][1] 代表数字长度为len不含49但是以9开头的个数(显然dp[len][1]包含在dp[len][0]中)

3.dp[len][2] 代表数字长度为len含有49的个数

 

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define ll long long
using namespace std;

const int maxn = 3005;
const int INF = 1e9;
const int mask = 0x7fff;

ll dp[25][3];
ll digit[25];
void init(){
    memset(dp, 0, sizeof(dp));
    dp[0][0] = 1;
    for(int i = 1; i < 21; i++)
    {
        dp[i][0] = 10 * dp[i - 1][0] - dp[i - 1][1];   //在前面添上0~9,要减去4加到9前面这种情况
        dp[i][1] = dp[i - 1][0];
        dp[i][2] = 10 * dp[i - 1][2] + dp[i - 1][1];
    }
}
int main()
{
    init();
    int t;
    ll n;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%I64d", &n);
        int len = 1;
        memset(digit, 0, sizeof(digit));
        while(n)
        {
            digit[len++] = n % 10;
            n /= 10;
        }
        ll ans = 0;
        bool flag = 0;
        for(int i = len - 1; i >= 1; i--)
        {
            ans += dp[i - 1][2] * digit[i];
            if(flag) ans += digit[i] * dp[i - 1][0];
            else if(digit[i] > 4) ans += dp[i - 1][1];
            if(digit[i + 1] == 4 && digit[i] == 9) flag = 1;
        }
        if(flag) ans++;
        printf("%I64d\n", ans);
    }
    return 0;
}

 

 

版权声明:本文为博主原创文章,未经博主允许不得转载。


  1. 站长,你好!
    你创办的的网站非常好,为我们学习算法练习编程提供了一个很好的平台,我想给你提个小建议,就是要能把每道题目的难度标出来就好了,这样我们学习起来会有一个循序渐进的过程!

  2. 换句话说,A[k/2-1]不可能大于两数组合并之后的第k小值,所以我们可以将其抛弃。
    应该是,不可能小于合并后的第K小值吧