UVA 136 & POJ1338 Ugly Numbers
来源:互联网 发布:idc机房网络架构 编辑:程序博客网 时间:2024/05/21 12:14
题目链接:POJ UVA
题目大意:
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.
把只含有2.3.5因数的数称为丑数,默认第一个丑数是1。
POJ是有多次询问,输出第n个丑数
UVA是询问第1500个丑数是多少。
思路:
利用STL的优先队列,创建一个小数优先的优先队列,然后每次取队头,分别乘以2.3.5,利用map看是否被放入过队列。从而得到按照大小顺序排列的丑数。
代码:
UVA
#include<bits/stdc++.h>using namespace std;typedef long long ll;int main(){ ll num=1; priority_queue<ll,vector<ll>,greater<ll> > q;//小数优先的优先队列 map<ll,ll> mp; int x[3]={2,3,5},cnt=1; q.push(num); mp[num]++; while(!q.empty()) { num=q.top(); q.pop(); if(cnt==1500){ cout<<"The 1500'th ugly number is "<<num<<"."<<endl; break; } for(int i=0;i<3;++i){ ll a=num*x[i]; if(mp[a]==0){//对取过的丑数进行标记 q.push(a); mp[a]++; } } cnt++; } return 0;}
POJ
#include<iostream>#include<cstdlib>#include<queue>#include<map>#include<algorithm>using namespace std;typedef long long ll;int main(){ ios::sync_with_stdio(false); ll num=1; ll ugly[1510];//打表存数,对于询问直接输出 priority_queue<ll,vector<ll>,greater<ll> > q; map<ll,ll> mp; int x[3]={2,3,5},cnt=1; q.push(num); mp[num]++; while(!q.empty()) { num=q.top(); q.pop(); ugly[cnt]=num; if(cnt==1500) break; for(int i=0;i<3;++i){ ll a=num*x[i]; if(mp[a]==0){ q.push(a); mp[a]++; } } cnt++; } int n; while(cin>>n&&n) cout<<ugly[n]<<endl; return 0;}
阅读全文
1 0
- UVA 136 & POJ1338 Ugly Numbers
- poj1338(Ugly Numbers)
- poj1338 Ugly Numbers(技巧)
- 枚举 poj1338 Ugly Numbers
- POJ1338 Ugly Numbers
- poj1338 Ugly Numbers
- POJ1338 Ugly Numbers
- POJ1338 Ugly Numbers
- poj1338——Ugly Numbers
- UVa 136 - Ugly Numbers
- UVa 136 - Ugly Numbers
- UVa 136 - Ugly Numbers
- UVA - 136 Ugly Numbers
- UVA 136 Ugly Numbers
- Uva - 136 - Ugly Numbers
- UVA 136 Ugly Numbers
- UVA 136 Ugly Numbers
- UVA - 136 Ugly Numbers
- spark源码阅读一-spark读写hbase代码分析
- 【基础题】--实现二叉树的前序 / 中序 / 后序非递归遍历
- 分享一些自己的学习过程和学习方法
- Tesseract in Java
- 接口测试学习
- UVA 136 & POJ1338 Ugly Numbers
- Retrofit的简单使用
- Unity游戏接入百度移动广告
- Shell变量作用域
- 拼多多前端笔试题
- leetcode-109 Convert Sorted List to Binary Search Tree
- 使Java线程停止的两种方法
- 生成一个对象的细节过程
- java多线程学习