HDU 1058 [Humble Numbers] 数组生成

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1058

题目大意:Humble number是质因数只可能有2,3,5,7的数。输入n,格式化输出第n个Humble number

关键思想:Humble数可以表示成pow(2,i)+pow(3,j)+pow(5,k)+pow(7,l).可以暴力枚举。

也可以DP生成数组dp[n]=min(2*dp[i],3*dp[j],5*dp[k],7*dp[l])。

代码里是第二种方法,代码如下

//生成数组的方式值得学习 
#include<iostream>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
int a[5888];

int main(){
	int cnt=1;
	int n,p2,p3,p5,p7;
	a[1]=1;
	p2=p3=p5=p7=1;
	//很精妙  
	while(a[cnt]<2000000000){
		cnt++;
		int t2=2*a[p2],t3=3*a[p3],t5=5*a[p5],t7=7*a[p7];
		a[cnt]=min(min(min(t2,t3),t5),t7);
		if(a[cnt]==t2)p2++;
		if(a[cnt]==t3)p3++;
		if(a[cnt]==t5)p5++;
		if(a[cnt]==t7)p7++;
	}
	/*举个例子:如果结果是p2当前所指的数字X2生成的数,
	那么下一个数不可能是p2当前所指的数X2而可能是数组里下一个数X2。 
	*/ 
	while(cin>>n&&n){
		if(n%10==1&&n%100!=11)printf("The %dst humble number is %d.\n",n,a[n]);//111输出也是th 
		else if(n%10==2&&n%100!=12)printf("The %dnd humble number is %d.\n",n,a[n]);
		else if(n%10==3&&n%100!=13)printf("The %drd humble number is %d.\n",n,a[n]);
		else printf("The %dth humble number is %d.\n",n,a[n]); 
	}
	return 0;
}

  

    原文作者:哇咔咔咔
    原文地址: https://www.cnblogs.com/G-M-WuJieMatrix/p/6420552.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞