《算法竞赛入门经典2ndEdition 》例题5-7 丑数(Ugly Numbers, Uva136)

之前做过一道题叫做Humble Numbers, 与此题非常相似,大家可以自行百度一下,感觉比这道题要难很多,
http://acm.hdu.edu.cn/showproblem.php?pid=1058
http://noi.openjudge.cn/ch0405/1249/
Humble Numbers这道题目据说曾经是Google、Hulu的面试题。对于任意一个丑数f[i],都是由它前面的丑数乘以2,3,5或者7得到的。
自认为这种类似DP的记录状态,然后后面的数都由前面的数乘上2,3,5来得到的方法要比优先队列的方法好,优先队列的方法之中似乎记录了一些不必要的值,因此需要用到long long,下面这个程序是我的方法,自认为比较好:

#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int num[2000];

int i, j, k;

int min3(int a, int b, int c)
{
  int x = min(a, b);
  x = min(x, c);
  if(x == a) i++;
  if(x == b) j++; 
  if(x == c) k++; 
  return x;
}

int main()
{
  i = 1; j = 1; k = 1;
  num[0] = 0;
  num[1] = 1;
  for(int s = 2; s <= 1510; s++)
    num[s] =  min3(2*num[i], 3*num[j], 5*num[k]);
  cout<<"The 1500'th ugly number is "<<num[1500]<<".\n";
  getchar();
  return 0;
} 

下面这个网址对于优先队列的讲解感觉比较好,大家可以看一看。http://blog.sina.com.cn/s/blog_959bf1d3010191h1.html
下面这个是我按照书中给出的优先队列方法写的。

#include <cstdio>
#include <iostream>
#include <queue>
#include <vector>
#include <set>
#include <algorithm>

using namespace std;

typedef long long LL;
priority_queue<LL, vector<LL>, greater<LL> > pq;
set<LL> s;

int main()
{
  int multi[3] = {2,3,5};
  pq.push(1);
  s.insert(1);
  for(int i = 1; ; i++)
  {
    LL x = pq.top();
    pq.pop();
    if(i == 1500) 
    {
      cout<<"The 1500'th ugly number is "<<x<<".\n";
      getchar();
      return 0;
    }
    for(int j = 0; j < 3; j++)
    {
      LL y = x * multi[j];
      if(!s.count(y)) 
      {
        s.insert(y);
        pq.push(y);
      }
    }
  }  
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值