紫书刷题进行中,题解系列【GitHub|CSDN】
例题5-7 UVA136 Ugly Numbers(20行AC代码)
思路分析
直接暴力求解会超时,因此可采用优先队列构造法
从1开始,对于x,2x,3x,5x均为丑数
因此,初始将1推入优先队列,每次从优先队列取出最小值,然后2x,3x,5x推入优先队列
有些数可能会重复构造,因此用set去重
注意点
- 可能会溢出,用long long类型
- 优先队列定义优先级
AC代码(C++11,优先队列,set去重,丑数构造)
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main() {
LL a[3] = {2,3,5}, t, num=0;
priority_queue<LL, vector<LL>, greater<LL> > pq; // 优先队列
set<LL> _set; // 判重
pq.push(1L); _set.insert(1L); // 第一轮
while (true) {
t = pq.top(); pq.pop(); num ++;
if (num == 1500) break;
for (int i = 0; i < 3; i ++) // x,2x,3x,5x构造丑数
if (_set.find(t*a[i]) == _set.end()) {
pq.push(t*a[i]);
_set.insert(t*a[i]);
}
}
printf("The 1500'th ugly number is %lld.\n", t);
return 0;
}
来源:CSDN
作者:是阿俊呐
链接:https://blog.csdn.net/qq_40738840/article/details/104200997