UVA - 136 Ugly Numbers (有关set使用的一道题)

Ugly numbers are numbers whose only prime factors are 2, 3 or 5.

The sequence1, 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 ‘’ replaced by the numbercomputed.

Sample OutputThe 1500'th ugly number is .

把只包含因子2、3和5的数称作ugly numbers

例如6、8都是丑数,但20不是,因为它包含因子4。

本题要求输出第1500个丑数,用set直接判重输出

WA了一次发现UVA不支持#include<buts/stdc++.h>…………

set的用法:set<类型>名字;

例如set<int>se;set<string>se;

自己定义的结构体什么的也可以往里面塞

基本操作对集合a中元素的有

插入元素:a.insert(1);

删除元素(如果存在):a.erase(1);

判断元素是否属于集合:if(a.find(1)!=a.end())

返回集合元素的个数:a.size()

将集合清为空集 :a.clear ()

set可以解决去重和排序问题。

set中每个元素最多只出现一次

set中的元素已经从小到大排序好

如何通过迭代器从小到大遍历所有元素 

for (set<string>::iterator i = d.begin(); i != d.end(); i++)  

cout << *i << endl;

#include <cstdio>
#include <set>
#include <algorithm>
using namespace std; set<long long>a;
int ref[3]={2,3,5};
int main()
{
int m=1;
a.insert(1);//默认1位第一个丑数
set<long long>::iterator it=a.begin();
//set<long long>::iterator it;一样的
//迭代器对象代表容器中的确定的地址 ,理解成将a这个容器的首地址给了it
while(m<=1600)
{
it=a.begin();
for(it;it!=a.end()&&m<=1600;it++)//从小到大遍历元素,中间多了一个判断m数值的条件
{
for(int j=0;j<3;j++)
{
long long tmp=(*it)*ref[j];//使值对应乘一遍2、3、5
if(a.find(tmp)==a.end())//find()--返回一个指向被查找到元素的迭代器,此处为判断整个set数组中是否有tmp
{
a.insert(tmp);//如果没有就添加tmp
m++;//丑数+1
}
}
}
}
m=1;
it=a.begin();
for(it;it!=a.end()&&m++<1500;it++);//从小到大遍历set数组,注意此处的;
//一直到m=1499的时候,数组才停止,此时it++,正好对应了第1500个
printf("The 1500'th ugly number is %lld.\n",*it);//nice,完美,没毛病
return 0;
}
上一篇:[java学习笔记]java语言基础概述之内存的划分&堆和栈


下一篇:c# 模拟网易足彩算法