STL醜數(set+優先佇列)

Combatting發表於2018-01-29

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

Sample Output

The 1500'th ugly number is .


問題連結UVA136 Ugly Numbers

set做法

注意while迴圈中不能用ugly.size()作為迴圈控制條件,這樣會使有的元素還沒有加入到集合中
#include <iostream>  
#include <cstdio>  
#include <set>  
  
using namespace std;  
  
#define MAXN 1500  
  
typedef unsigned long long ULL;  
  
set<ULL> ugly;  
  
int main(void)  
{  
    int count;
    ugly.insert(1);
    count=0;
    set<ULL>::iterator iter = ugly.begin();//迭代器傳送 
    while(++count<MAXN)
    {
    	int t=*iter;
    	ugly.insert(t*2);
    	ugly.insert(t*3);
    	ugly.insert(t*5);
    	iter++;
	}
    printf("The 1500'th ugly number is %llu.\n", *iter);  
    return 0;  
}  
優先佇列
#include<iostream> 
#include<vector>
#include<queue>
#include<set>
using namespace std;
typedef long long LL;
const int coeff[3] = {2, 3, 5};
int main() 
{
	priority_queue<LL, vector<LL>, greater<LL> > pq;
	set<LL> s;
	pq.push(1);
	s.insert(1);
	for(int i = 1; ; i++) 
	{
		LL x = pq.top(); pq.pop();
		if(i == 1500) 
		{
			cout << "The 1500'th ugly number is " << x << ".\n";
			break;
		}
		for(int j = 0; j < 3; j++) 
		{
			LL x2 = x * coeff[j];
			if(!s.count(x2)) 
			{ 
				s.insert(x2); 
				pq.push(x2); 
			}
		}
	}
	return 0;
}


相關文章