[关闭]
@Chilling 2016-08-19T11:05:49.000000Z 字数 1833 阅读 835

HDU-1058: Humble Numbers

DP


Description

A number whose only prime factors are 2,3,5 or 7 is called a humble number. The sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, ... shows the first 20 humble numbers.

Write a program to find and print the nth element in this sequence

Input

The input consists of one or more test cases. Each test case consists of one integer n with 1 <= n <= 5842. Input is terminated by a value of zero (0) for n.

Output

For each test case, print one line saying "The nth humble number is number.". Depending on the value of n, the correct suffix "st", "nd", "rd", or "th" for the ordinal number nth has to be used like it is shown in the sample output.

Sample Input

1
2
3
4
11
12
13
21
22
23
100
1000
5842
0

Sample Output

The 1st humble number is 1.
The 2nd humble number is 2.
The 3rd humble number is 3.
The 4th humble number is 4.
The 11th humble number is 12.
The 12th humble number is 14.
The 13th humble number is 15.
The 21st humble number is 28.
The 22nd humble number is 30.
The 23rd humble number is 32.
The 100th humble number is 450.
The 1000th humble number is 385875.
The 5842nd humble number is 2000000000.

分析:每个数都可以分解成有限个2,3,5,7的乘积,dp方程为:
dp[i]=f[i]=min(f[x2]*2,min(f[x3]*3,min(f[x5]*5,f[x7]*7)))
找到比f[i-1]大且最小的数,在这里用到了滚动查找;
下面详细解释:
x2表示s[]数组中,下标为a的数 * 2 可能得到当前的s[i];若是则++
x3表示s[]数组中,下标为b的数 * 3 可能得到当前的s[i];若是则++
x5表示s[]数组中,下标为b的数 * 5 可能得到当前的s[i];若是则++
x7表示s[]数组中,下标为b的数 * 7 可能得到当前的s[i];若是则++
求出他们中的min,则为f[i];
这么机智……一看就不是自己想到的ORZ


  1. #include<stdio.h>
  2. #include<algorithm>
  3. using namespace std;
  4. int main()
  5. {
  6. int n,i,j;
  7. int x2=0,x3=0,x5=0,x7=0;
  8. int s[5842]={1};
  9. for(i=1;i<5842;i++) //丑数的2,3,5,7倍也是丑数
  10. {
  11. s[i]=min(min(min(s[x2]*2,s[x3]*3),s[x5]*5),s[x7]*7);
  12. if(s[i]==s[x2]*2)
  13. x2++;
  14. if(s[i]==s[x3]*3)
  15. x3++;
  16. if(s[i]==s[x5]*5)
  17. x5++;
  18. if(s[i]==s[x7]*7)
  19. x7++;
  20. }
  21. while(scanf("%d",&n),n)
  22. {
  23. if(n%10==1&&n%100!=11)
  24. printf("The %dst humble number is %d.\n",n,s[n-1]);
  25. else if(n%10==2&&n%100!=12)
  26. printf("The %dnd humble number is %d.\n",n,s[n-1]);
  27. else if(n%10==3&&n%100!=13)
  28. printf("The %drd humble number is %d.\n",n,s[n-1]);
  29. else
  30. printf("The %dth humble number is %d.\n",n,s[n-1]);
  31. }
  32. return 0;
  33. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注