這是一道讓我收益不少的題目,這道題目自己沒有遇到過,是通過一個老師講解得來的。
==========================================================================================================
題目描述:
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...
shows the first 10 ugly numbers. By convention, 1 is included.
Given the integer n,write a program to find and print the n'th ugly number.
輸入格式
Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.
輸出格式
For each line, output the n’th ugly number .:Don’t deal with the line with n=0.
輸入樣例
1
2
9
0
輸出樣例
1
2
10
==========================================================================================================
==========================================================================================================
#include <iostream>
#include <queue>
#include <functional>
using namespace std;
typedef pair<unsigned long, int> node;
int main()
{
unsigned long uglyNumber[1500];//又是“記憶搜索”,爲以後每次查詢提供答案
priority_queue< node, vector<node>, greater<node> > queue;
queue.push(make_pair(1, 2));
for (int i = 0; i < 1500; ++i) {
node t = queue.top();
queue.pop();
switch (t.second) {
case 2:
queue.push(make_pair(t.first * 2, 2));
case 3:
queue.push(make_pair(t.first * 3, 3));
case 5:
queue.push(make_pair(t.first * 5, 5));
}
uglyNumber[i] = t.first;
}
int n;
cin >> n;
while (n > 0) {
cout << uglyNumber[n - 1] << endl;
cin >> n;
}
return 0;
}
==========================================================================================================