POJ 1338 Ugly Numbers(丑数)
2016-05-12 15:43
211 查看
一.问题分析
首先啊。。。。这种题在有了大致的思路了以后就不要再照着书去实现了,真的就没什么意思了》》但就这个问题本身而言还是蛮有意思的嘛,用到了集合法对元素进行判重,其实map也是可以实现的嘛,还有就是一开始我的想法是按照素数分解每个丑数都可以分解成为2^z*3^x*5^y,这种形式,但是一时也没找出好的方案来生成合理有序的xyz序列(其实根本就是没有动脑子吧,下次中午要好好睡觉!),最后发现如果x是丑数那么2x,3x,5x,也一定都是丑数,这样每次生成的方案就十分简单了,再利用优先队列的性质,问题很容易就解决了。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
1210#include <iostream> #include <cstring> #include <queue> #include <set> using namespace std; int n; int op[]={2,3,5}; int main() { //freopen("input.txt","r",stdin); while(cin>>n) { if(n==0) break; priority_queue< long long ,vector<long long>,greater<long long> > pq; set<long long> s; pq.push(1); s.insert(1); for(int i=1;i<=n;i++) { if(i==n) cout<<pq.top()<<endl; else { long long temp=pq.top(); pq.pop(); //cout<<temp<<" "; for(int j=0;j<3;j++) { //cout<<"("<<temp<<"*"<<op[j]<<") "; long long x; x=temp*op[j]; if(!s.count(x)) { pq.push(x); s.insert(x); } } } } } return 0; }
三.优先队列的注意点
注意,优先队列是队列里的元素按照一定的优先级进行排列的队列,默认的情况下是数越大优先级越大,还可以通过重写cmp函数来实现优先级大小比较的设定,但是如果希望小的数字优先级高,有种简单的方法#include <iostream>priority_queue< long long ,vector<long long>,greater<long long> > pq;
相关文章推荐
- JVM调优总结
- Java 中的super和this区分
- 静态编译
- Facebook产品总监NB产品14个必考题
- 13.View的事件分发机制——dispatchTouchEvent详解
- HDU 2255 奔小康赚大钱 (二分图:KM算法)
- Select at least one project的解决方法
- 为啥UI设计师要学习产品思维?
- gcc & makefile
- 【java开发系列】—— 自定义注解
- HashMap与ConcurrentHashMap的区别
- 移动应用UI规范
- Yii 2.0邮箱类简单应用
- JVM常见配置汇总
- 微信 安卓 无法支持keydown keypress keyup
- android string.xml 前后加空格
- {实战}Docker Machine + Compose + Swarm
- 设计师思维模型之用户模型
- Android自定义下载状态栏
- AangularJs动态时间例子