hdu1058 Humble Numbers && hdu3199 Hamming Problem(简单dp)

本文介绍了一种使用动态规划解决丑数问题的方法,并提供了两个具体的实现案例:一是求解特定形式的丑数序列,二是解决更一般化的丑数生成问题。通过优化生成过程减少计算量,确保了算法效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以前用优先队列和set做过丑数,这种题也可以用dp。


先是1058,这种dp用一层for就可以了,思路很清晰,根据已有的生成未知的。

输出格式注意11、12、13的情况是100的余数,这点很操蛋,英语序数词没学好。

#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <string.h>
#include <cmath>

using namespace std;

const int N = 10010;
const int INF = 1e8;

__int64 dp[N];

int main()
{
  //  freopen("in.txt", "r", stdin);
    int a, b, c, d, n;
    dp[1] = 1;
    a = b = c = d = 1;
    for(int i = 2; i <= 5843; i ++)
    {
        dp[i] = min(min(dp[a] * 2, dp[b] * 3), min(dp[c] * 5, dp[d] * 7));
        if(dp[i] == dp[a] * 2) a ++;
        if(dp[i] == dp[b] * 3) b ++;
        if(dp[i] == dp[c] * 5) c ++;
        if(dp[i] == dp[d] * 7) d ++;
    }
    while(~scanf("%d", &n) && n)
    {
        if(n % 10 == 1 && n % 100 != 11) printf("The %dst humble number is %I64d.\n", n, dp[n]);
        else if(n % 10 == 2 && n % 100 != 12) printf("The %dnd humble number is %I64d.\n", n, dp[n]);
        else if(n % 10 == 3 && n % 100 != 13) printf("The %drd humble number is %I64d.\n", n, dp[n]);
        else printf("The %dth humble number is %I64d.\n", n, dp[n]);
    }
    return 0;
}


3199数据量吓人,但尽量少生成就可以了。

#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <string.h>
#include <cmath>

using namespace std;

const int N = 10010;
const int INF = 1e8;

__int64 dp[N];

int main()
{
  //  freopen("in.txt", "r", stdin);
    int a, b, c, num1, num2, num3, n;
    while(~scanf("%d%d%d%d", &num1, &num2, &num3, &n))
    {
        dp[0] = 1;
        a = b = c = 0;
        for(int i = 1; i <= n; i ++)
        {
            dp[i] = min(min(dp[a] * num1, dp[b] * num2), dp[c] * num3);
            if(dp[i] == dp[a] * num1) a ++;
            if(dp[i] == dp[b] * num2) b ++;
            if(dp[i] == dp[c] * num3) c ++;
        }
        printf("%I64d\n", dp[n]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值