做者自轉,原文連接:http://blog.csdn.net/nmlh7448...ios
規定質因子只有2,3,5的數是Ugly Numbers。對於給定的n,輸出第n個Ugly Numbers。(n<=1500)數組
能夠先求出前1500個Ugly Numbers,而後直接輸出便可。所以能夠獲得全部的Ugly Numbers都是2^a3^b5^c,其中a, b, c>=0.直接枚舉a, b, c沒有規律,因此能夠使用隊列的數據結構。首先將1壓入隊列,而後循環:取隊列首元素e,檢查e是否出現過,出現過就繼續,沒有出現過就將 e 儲存到一個數組裏,將e2,e3,e*5壓入隊列。這樣以後能夠高效地選出全部的Ugly Numbers。能夠再度加入一個優化,使用優先隊列,那麼能夠保證數字是嚴格從小到大出現的。數據結構
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> #include<queue> #include<set> using namespace std; long n, v, w; long long u[2000]; struct cmp { bool operator() (long long a, long long b) { return a>b; } }; priority_queue<long long, vector<long long>,cmp> q; bool find(long long k) { for(long i=1; i<=v; i++) if(u[i]==k) return true; return false; } int main() { freopen("in.in", "r", stdin); q.push(1); long long a; w = 1; while(v <= 1500) { a = q.top(); q.pop(); if(!find(a)) { u[++v] = a; q.push(a * 2); q.push(a * 3); q.push(a * 5); } } while(~scanf("%d", &n) && n) cout << u[n] << endl; return 0; }
原本判重是用set實現的,可是效率過低,反而不如暴力的一位數組。優化