POJ1338 Ugly Numbers 堆优化+模拟

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. 

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

2.题意概述:

定义丑数是质因子只有2、3、5的数,简单说就是可以写成2^a*3^b^5^c(a,b,c>=0)要你求第n个丑数

3.解题思路:

可以考虑用一个小顶堆去维护丑数,一个数组来记录前N个丑数,每次拿出堆顶,判断是否重复,然后在分别乘以二、三、五放回堆中,为了避免重复计算,预处理一下再查询,这样查询就是线性的

196K0MS

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值