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

来源:互联网 发布:php链接mysql数据库 编辑:程序博客网 时间:2024/04/30 06:32

以前用优先队列和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;}


0 0