uvaoj 136 Ugly Numbers 優先隊列使用

uvaoj 136 Ugly Numbers 優先隊列使用
醜數是不能被除2,3,5以外的其他素數整除的數,把醜數從小到大排列,1,2,3,4,5,6,8,9,10,12,15.......,求第1500個醜數。
對於醜數x,2x,3x,5x,都是醜數,我們可以從小到大生成醜數,將生成的醜數保存起來,每次取出來最小的一個,然後生成三個醜數,但這個會重複,可以使用set去重。
代碼如下:
/*************************************************************************
	> File Name: 136.cpp
	> Author: gwq
	> Mail: [email protected] 
	> Created Time: 2015年01月21日 星期三 16時27分34秒
 ************************************************************************/

#include <cmath>
#include <ctime>
#include <cctype>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>

#define INF (INT_MAX / 10)
#define clr(arr, val) memset(arr, val, sizeof(arr))
#define pb push_back
#define sz(a) ((int)(a).size())

using namespace std;
typedef set<int> si;
typedef vector<int> vi;
typedef map<int, int> mii;
typedef long long ll;

const double esp = 1e-5;

ll mp[] = {2, 3, 5};

int main(int argc, char *argv[])
{
	priority_queue<ll, vector<ll>, greater<ll> > q;
	set<ll> s;
	q.push(1);
	s.insert(1);
	int cnt = 1;
	ll ans = 0;
	for (cnt = 1; ; ++cnt) {
		ll t = q.top();
		q.pop();
		if (cnt == 1500) {
			ans = t;
			break;
		}
		for (int i = 0; i < 3; ++i) {
			ll x = t * mp[i];
			if (!s.count(x)) {
				q.push(x);
				s.insert(x);
			}
		}
	}

	printf("The 1500'th ugly number is %lld.\n", ans);
	return 0;
}


發佈了124 篇原創文章 · 獲贊 15 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章