题目地址:
http://acm.hdu.edu.cn/showproblem.php?pid=1058
题目概述:
定义因子只有2,3,5,7的数为humble number,输入n,求出第n个humble number。规定1为第1个humble number。
大致思路:
刚开始看到n小于5842时写的暴力求所有的humble number结果TLE,强行打表被卡代码长度,丧心病狂优化暴力反而时间变长了23333
最后忍不住上了STL,用priority_queue来维护所有humble number的序列,每次取出队列头的一个数,将这个数乘2,3,5,7之后push进队列中就可以了,不过需要注意去重。
最后说一句,真的要好好学英文!!!我就是因为序数词的结尾写错了白白WA了3遍!!!
代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cmath> 5 #include <vector> 6 #include <ctime> 7 #include <map> 8 #include <stack> 9 #include <queue> 10 #include <cstring> 11 #include <algorithm> 12 using namespace std; 13 14 #define sacnf scanf 15 #define scnaf scanf 16 #define maxn 6000 17 #define maxm 26 18 #define inf 1061109567 19 #define Eps 0.00001 20 const double PI=acos(-1.0); 21 #define mod 1000033 22 #define MAXNUM 10000 23 void Swap(int &a,int &b) {int t=a;a=b;b=t;} 24 int Abs(int x) {return (x<0)?-x:x;} 25 typedef long long ll; 26 typedef unsigned int uint; 27 28 ll f[maxn]; 29 30 ll d[]={2,3,5,7}; 31 32 void init() 33 { 34 int cnt=1; 35 priority_queue<ll,vector<ll>,greater<ll> > q; 36 q.push(1); 37 while(cnt<=5842) 38 { 39 ll x=q.top();q.pop(); 40 if(f[cnt-1]==x) continue; 41 f[cnt++]=x; 42 for(int i=0;i<4;i++) 43 { 44 ll ans=x*d[i]; 45 if(ans>0&&ans<=2000000000) 46 { 47 q.push(ans); 48 } 49 } 50 } 51 } 52 53 int main() 54 { 55 //freopen("data.in","r",stdin); 56 //freopen("data.out","w",stdout); 57 //clock_t st=clock(); 58 int n;init(); 59 while(~scanf("%d",&n)) 60 { 61 if(n==0) break; 62 printf("The %d",n); 63 if(n%10==1&&n%100!=11) printf("st"); 64 else if(n%10==2&&n%100!=12) printf("nd"); 65 else if(n%10==3&&n%100!=13) printf("rd"); 66 else printf("th"); 67 printf(" humble number is %lld. ",f[n]); 68 } 69 //clock_t ed=clock(); 70 //printf(" Time Used : %.5lf Ms. ",(double)(ed-st)/CLOCKS_PER_SEC); 71 return 0; 72 }