UVA

来源:互联网 发布:天龙八部手游染色数据 编辑:程序博客网 时间:2024/04/29 21:41
/*  思路:  从小到大生成所有的丑数,最小的丑数为1,对于任意丑数x,2x,3x,5x也是丑数;  这样就可以用一个(数值越小,优先级越大的)优先队列来保存所有已生成的丑数,每次取出最小的丑数,生成3个新的丑数入队(生成的3个中,并不一定都是新的丑数,但只让新的入队),直到取出的丑数是第1500个丑数    但要注意:  同一个丑数可能有多种生成方式,例如(10 == 2 * 5 == 5 * 2),所以需要判断一个丑数是否有生成过,如果没有,才将其入队 */
#include <iostream>#include <vector>#include <queue>#include <set>using namespace std;typedef long long ll;const int coeff[3] = {2, 3, 5};int main(){cin.tie(0);cin.sync_with_stdio(false);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 << "." << endl;break;}for (int j = 0; j < 3; j++){ll tp = x * coeff[j];if (!s.count(tp)){pq.push(tp);s.insert(tp);}}}return 0;} 


原创粉丝点击