1.题目描述:
Ugly Numbers
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 23957 | Accepted: 10597 |
Description
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.
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.
Input
Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.
Output
For each line, output the n’th ugly number .:Don’t deal with the line with n=0.
Sample Input
1 2 9 0
Sample Output
1 2 10
Source
New Zealand 1990 Division I,UVA 136
2.题意概述:
定义丑数是质因子只有2、3、5的数,简单说就是可以写成2^a*3^b^5^c(a,b,c>=0)要你求第n个丑数
3.解题思路:
可以考虑用一个小顶堆去维护丑数,一个数组来记录前N个丑数,每次拿出堆顶,判断是否重复,然后在分别乘以二、三、五放回堆中,为了避免重复计算,预处理一下再查询,这样查询就是线性的
196K | 0MS |
4.AC代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <functional>
#include <cmath>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#include <ctime>
#define INF 0x7fffffff
#define maxn 100100
#define N 1555
#define eps 1e-6
#define pi acos(-1.0)
#define e 2.718281828459
#define mod (int)1e9 + 7
using namespace std;
typedef long long ll;
ll a[N];
void solve()
{
int cnt = 1;
a[0] = INF;
priority_queue<ll, vector<ll>, greater<ll>> heap;
heap.push(1);
while (cnt <= 1500)
{
ll temp = heap.top();
heap.pop();
if (temp == a[cnt - 1])
continue;
a[cnt++] = temp;
heap.push(temp * 2);
heap.push(temp * 3);
heap.push(temp * 5);
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
long _begin_time = clock();
#endif
int n;
solve();
while (~scanf("%d", &n), n)
printf("%lld\n", a[n]);
#ifndef ONLINE_JUDGE
long _end_time = clock();
printf("time = %ld ms.", _end_time - _begin_time);
#endif
return 0;
}