HDU_1058 Humble Numbers(DP)

  动态规划题,F[n] 可由2, 3, 5, 7与F[n-1]的乘积得到,取这四个数的的最小值,就是当前F[n]的值,即F[n] = min{F[n-1]*2, F[n-1]*3, F[n-1]*5, F[n-1]*7}。

  前6个数的递归过程:

       n1 = 1;

  n2 = min{1*2, 1*3,1*5,1*7} = 2;

  n3 = min{2*2, 1*3, 1*5, 1*7} = 3;

  n4 = min{2*2, 2*3, 1*5, 1*7} = 4;

  n5 = min{3*2, 2*3, 1*5, 1*7} = 5;

  n6 = min{3*2, 2*3, 2*5, 1*7} = 6;

  代码如下:

#include <stdio.h>
int min(int x, int y)
{
return x < y ? x : y;
}
int main()
{
int i, a, b, c, d, n;
int num[5850];
num[
1] = 1;
a
= b = c = d = 1;
for(i = 2; i <= 5842; i++)
{
num[i]
= min(num[a]*2, min(num[b]*3, min(num[c]*5, num[d]*7)));
if(num[i] == num[a]*2) a++;
if(num[i] == num[b]*3) b++;
if(num[i] == num[c]*5) c++;
if(num[i] == num[d]*7)   d++;
}
while(scanf("%d", &n), n)
{
printf(
"The %d", n);
if(n%100 != 11 && n%10 == 1) printf("st");
else if(n%100 != 12 && n%10 == 2) printf("nd");
else if(n%100 != 13 && n%10 == 3) printf("rd");
else printf("th");
printf(
" humble number is %d.\n", num[n]);
}
return 0;
}
posted @ 2011-08-04 08:14  AC_Von  阅读(1047)  评论(0编辑  收藏  举报