我是靠谱客的博主 踏实金针菇,最近开发中收集的这篇文章主要介绍HDU-3555-Bomb【数位dp】,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述


HDU-3555-Bomb【数位dp】


            Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)

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.

题目链接:HDU-3555

题目大意:在[0,n]的范围内存在多少个数字含有49

题目思路:数位dp。

    状态转移:

      dp[i][0]代表长度为 i 并且不含有49的数字的个数;

      dp[i][1]代表长度为 i 并且不含有49,但是最高位是9的数字的个数;

      dp[i][2]代表长度为 i 并且含有49的数字的个数。

以下是代码:

#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
long long dp[25][10];
int dig[25];

void init()
{
    memset(dp,0,sizeof(dp));
    dp[0][0] = 1;
    for (int i = 1; i < 25; i++)
    {
        dp[i][0] = dp[i - 1][0] * 10 - dp[i - 1][1];//dp[i][0]高位随便加一个数字都可以,但是会出现49XXX的情况,要减去
        dp[i][1] = dp[i - 1][0];//在不含49的情况下高位加9
        dp[i][2] = dp[i - 1][2] * 10 + dp[i - 1][1];//在含有49的情况下高位随便加一位或者不含49但高位是9,在前面最高位加上4就可以了
    }
}

long long solve(long long num)
{
    memset(dig,0,sizeof(dig));
    int k = 1;
    while(num > 0)
    {
        dig[k++] = num % 10;
        num /= 10;
    }
    long long ans = 0;
    int flag = 0;
    for (int i = k - 1; i > 0; i--)
    {
        ans += dp[i - 1][2] * dig[i];
        if (flag) ans += dp[i - 1][0] * dig[i];
        if (!flag && dig[i] > 4) ans += dp[i - 1][1];  //这里我不理解为什么不是 >=4 
        if (dig[i] == 9 && dig[i + 1] == 4) flag = 1;
    }
    return ans;
}
int main(){
    int t;
    init();
    cin >> t;
    while(t--)
    {
        long long n;
        cin >> n;
        cout << solve(n + 1) << endl;
    }
    return 0;
}

最后

以上就是踏实金针菇为你收集整理的HDU-3555-Bomb【数位dp】的全部内容,希望文章能够帮你解决HDU-3555-Bomb【数位dp】所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部