UVA136 Ugly Numbers(优先队列应用)

来源:互联网 发布:飞龙淘宝小号浮云网 编辑:程序博客网 时间:2024/05/29 18:02

优先队列:“急诊病人插队”

priority_queue<int> pq声明优先队列

"越小的整数优先级越低的队列"

push()入队

pop()出队

top()取队首元素

这个题像了一会,纠结在为什么i == 1500

时停,原因就在于这个大循环每次会把最小的那个整数提出来,制造3个新的丑数,然后出队。这样每一循环,按小到大顺序出队一个丑数,直到1500个

#include<iostream>#include<vector>#include<queue>#include<set>using namespace std;typedef long long LL;const int coeff[3] = {2, 3, 5};//coeff数组存放最基础的丑数2,3,4int main(){    priority_queue<LL, vector<LL>, greater<LL> > pq;//定义优先队列    set<LL> s;//集合s作用是    pq.push(1);//把1入队    s.insert(1);//集合中插入1    for(int i  = 1; ; i++) {        LL x = pq.top(); pq.pop();//把优先队列中最小的数放到x里, 把x出队        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];//用x生成3个丑数            if(!s.count(x2)) { s.insert(x2); pq.push(x2); }//如果这个数没出现过,就入队,并且插入到集合中        }    }    return 0;}

0 0
原创粉丝点击