题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1058
原题:
Humble Numbers
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 17284 Accepted Submission(s): 7512
Write a program to find and print the nth element in this sequence
1 2 3 4 11 12 13 21 22 23 100 1000 5842 0
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.
初看此题,题目要求我们解决两个问题:
1、是第几的问题,求出数组,数组的第几个数该如何表达,这用到英文知识:
一般来说个位数是1为st,个位数为2是nd,个位数为3是rd;但是有例外,11, 12 ,13均为th,同时111,112,113均为th,除此之外,其他都是th;
2、就是求所要求的一个数组(至于为什么是数组,要想不超时,就把所有数据先弄出来,输什么就出第几个就是了,不用重复计算),题目中列举出前20个,这些数的特点是只能被1、2、3、5、7整除不能被其他素数整除,所以就可以换一个角度思考,所有的数都是2、3、5、7的2 3 5 7倍,不就可以了。
算法分析:
分析:用dp的思维解答
若一个数是Humble数,那么他的2、3、5、7倍仍然是Humble数。
定义a为第i个Humble数
a[n] = min( 2*a[m],3*a[n],5*a[k],7*a[l] ),m,n,k,l在被选择后彼此移动。
code:
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
int dp[6000];
int min(int a,int b)
{
return a<b?a:b;
}
void init()
{
int i,j,k,l,a1,a2,a3,a4,n;
dp[1]=1;
i=j=k=l=1;
for(n=2;n<6000;n++)
{
a1=dp[i]*2;
a2=dp[j]*3;
a3=dp[k]*5;
a4=dp[l]*7;
dp[n]=min(a1,min(a2,min(a3,a4)));
if(dp[n]==a1)
i++;
if(dp[n]==a2)
j++;
if(dp[n]==a3)
k++;
if(dp[n]==a4)
l++;
}
}
int main()
{
int n;
init();
while(scanf("%d",&n)!=EOF&&n)
{
printf("The ");
if(n%10==1&&n%100!=11)
printf("%dst humble number is %d.\n",n,dp[n]);
else if(n%10==2&&n%100!=12)
printf("%dnd humble number is %d.\n",n,dp[n]);
else if(n%10==3&&n%100!=13)
printf("%drd humble number is %d.\n",n,dp[n]);
else
printf("%dth humble number is %d.\n",n,dp[n]);
}
return 0;
}