之前做过一道题叫做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);
}
}
}
}