UVA136
来源:互联网 发布:js日历 编辑:程序博客网 时间:2024/06/05 01:37
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, 15, … shows the first 11
ugly numbers. By convention, 1 is included. Write a program to find
and print the 1500’th ugly number.
Input
There is no input to this program.
Output
Output should consist of a single line as shown below, with ‘< number>’ replaced
by the number computed.
Sample Output
The 1500’th Ugly Number is “< number >”.
Explanation
本题为优先队列的简单例题 题目大意介绍Ugly Numbers是指不能被2,3,5以外的其他素数整除的数。 把Ugly Numbers排序后得到1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …
求第1500个ugly number. 我们可以从小到大生成各个Ugly Number.
第一个是1,那么2、3、5也是,即对一个 Ugly Number X来说,
2*X,3*X,5*X也为Ugly Number. 需要注意的是,同一个Ugly Number有多重生成方式,那么我们需要考虑出现次数的问题.
这里用到了优先队列(priority queue)这一数据结构
普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征,即允许类似于“急诊病人插队”这样的事件发生。
Code
#include <iostream>#include <queue>#include <vector>#include <set>using namespace std;const int coeff[3] = {2, 3, 5}; //Ugly Number的扩展倍数typedef long long LL;int main(){ priority_queue<LL, vector<LL>, greater<LL> > pq; //定义优先队列,greater可以实现越小的整数优先级越大 set<LL> s; //因为要考虑Ugly Number的形成方式多样性,我们用到了set保证唯一次数 pq.push(1); s.insert(1); //起始Ugly Number为1 for(int i = 1; ; i++){ LL x = pq.top(); pq.pop(); //由于要取出优先级最高的所以要用top()而不是front() //cout << "i " << i <<" "<< x << endl; if(i == 1500){ cout << "The 1500'th ugly number is "<< x << "." << endl; break; } for(int j = 0; j < 3; j++){ LL y = x * coeff[j]; if(!s.count(y)){ s.insert(y); pq.push(y); } } } return 0;}
- uva136
- uva136
- UVA136
- UVA136
- UVA136 丑数
- uva136(优先队列)
- UVa136 priority_queue优先队列
- UVA136-Ugly Numbers
- UVa136 Ugly Numbers (priority_queue)
- UVA136 Ugly Numbers
- UVA136--Ugly Numbers
- STL-UVA136-Ugly Numbers
- uva136 Ugly numbers
- UVA136解题报告
- e5-7uva136 丑数
- Uva136——Ugly Numbers
- Uva136 丑数[优先队列]
- UVA136 Ugly Numbers(优先队列应用)
- Java 多态
- 【Scikit-Learn 中文文档】模型评估: 量化预测的质量
- 动态规划学习(4,深度优先搜索)
- 开发一流的 Android SDK:Fabric SDK 的创建经验
- ajax--3.转异步注意
- UVA136
- 集体智慧编程第三章 发现群组
- Django系列教程(6)-- HttpRequest对象和HttpResponse对象
- OCA Oracle Database 11g Administration I Exam Guide (Exam 1Z0-052).pdf 英文原版 免费下载
- 【Scikit-Learn 中文文档】模型持久化
- 【51nod】1019 逆序数(归并)
- Android Studio加载.9图报错
- Java微信公众平台开发之素材管理
- 交大oj-1022-Fib数列 C++ 解题报告