您的位置:首页 > 其它

HDU 1058 Humble Numbers

2014-07-04 16:14 330 查看
既然将这道题分类到动态规划的题目里面,一开始便是用动态规划的思想去思考。

一个上午毫无突破,看的人家的题解。

定义四个伪指针存放下标,分别表示的意思是在已知的丑数中,能够与2,3,5,7相乘的最小的数的下标。

上面这句话要好好体会。

也就是说dp[p1] * 2 能够得到一个新的丑数,其他三个以此类推。

但我们要求的是已知最大丑数中紧挨着的下一个丑数,那就是能够产生新丑数的最小值了。

即min(dp[p1] * 2, dp[p2] * 3, dp[p3] * 5, dp[p4] * 7);

另外需要注意的一点是,在DP()中会遇到某两个产生的丑数同为最小值的情况,那么对应的“指针”也要同时自增1。

比如i = 5的时候,p1 = 3, p2 = 2,此时dp[p1] * 2 == dp[p2] * 3 == 6;

如果只执行++p1不执行++p2的话,那么会漏掉9这个丑数。

最后吐槽一下蛋疼的输出。。

╮(╯▽╰)╭,何时才能不看题解,通过自己思考把dp题目A出来呢。。

//#define LOCAL
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int dp[5850];

inline int min(int a, int b, int c, int d)
{
a = min(a, b);
c = min(c, d);
return min(a, c);
}

void DP(void)
{
int i;
int p1 = 1, p2 = 1, p3 = 1, p4 = 1;
dp[1] = 1;
for(i = 2; i <= 5842; ++i)
{
dp[i] = min(dp[p1] * 2, dp[p2] * 3, dp[p3] * 5, dp[p4] * 7);
if(dp[i] == dp[p1] * 2)
++p1;
if(dp[i] == dp[p2] * 3)
++p2;
if(dp[i] == dp[p3] * 5)
++p3;
if(dp[i] == dp[p4] * 7)
++p4;
}
}

int main(void)
{
#ifdef LOCAL
freopen("1058in.txt", "r", stdin);
#endif

DP();
int n;
while(scanf("%d", &n) && n)
{
if(n % 10 == 1 && n % 100 != 11)
printf("The %dst humble number is ", n);
else if (n % 10 == 2 && n % 100 != 12)
{
printf("The %dnd humble number is ", n);
}
else if (n % 10 == 3 && n % 100 != 13)
{
printf("The %drd humble number is ", n);
}
else
printf("The %dth humble number is ", n);

printf("%d.\n", dp
);
}
return 0;
}


代码君
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: