• C++STL3--queue


    C++STL3--queue

    一、心得

    STL的这些东西用法都差不多

    二、介绍

    queue数据结构中的队列

    priority_queue优先队列,插入进去的元素都会从大到小排好序

    PS:在priority_queue<ll, vector<ll>, greater<ll> > pq;中
    第一个参数为数据类型,第二个参数为保存数据的容器(默认为vector<int>),第三个参数为元素比较函数(默认为less)。

    STL里面默认用的是 vector. 比较方式默认用 operator< , 所以如果你把后面俩个参数缺省的话,
    优先队列就是大顶堆,队头元素最大。

    三、实例

    UVA136 - Ugly Numbers

    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 ‘<number>’ replaced by the number
    computed.
    Sample Output
    The 1500'th ugly number is <number>.

    分析:

    丑数就是所有是2或3或5倍数的数。
    用优先队列从小到大排列丑数
    用set集合判断丑数是否重复

    代码:

     1 /*
     2 set的应用实例吧
     3 还有queue
     4 
     5 丑数就是所有是2或3或5倍数的数。
     6 用优先队列从小到大排列丑数
     7 用set集合判断丑数是否重复 
     8 */
     9 
    10 #include <iostream>
    11 #include <vector>
    12 #include <queue>
    13 #include <set>
    14 using namespace std;
    15 typedef long long LL;
    16 const int coeff[3]={2,3,5}; 
    17 
    18 int main(){
    19     /*
    20     PS:在priority_queue<ll, vector<ll>, greater<ll> > pq;中
    21     第一个参数为数据类型,第二个参数为保存数据的容器(默认为vector<int>),第三个参数为元素比较函数(默认为less)。
    22     */ 
    23     priority_queue<LL,vector<LL>,greater<LL> > pq;
    24     set<LL> s;
    25     pq.push(1);
    26     s.insert(1);
    27     for(int i=1;;i++){
    28         LL x=pq.top();
    29         pq.pop();
    30         if(i==1500){
    31             cout<<"The 1500'th ugly number is "<<x<<".
    ";
    32             break;
    33         }
    34         for(int j=0;j<3;j++){ 
    35             LL x2=x*coeff[j];
    36             if(!s.count(x2)){
    37                 s.insert(x2);
    38                 pq.push(x2);
    39             }
    40         }
    41         
    42     }
    43     return 0;
    44 }

  • 相关阅读:
    leetcode目录
    Windows下tuxedo配置
    实习总结
    n人比赛,可轮空,比赛轮数和场数
    Ubuntu中Eclipse安装与配置
    Lunix中文乱码解决方案
    tuxedo入门
    useradd和adduser的区别
    每个位上都是素数
    TUXEDO错误解决方案
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/6972733.html
Copyright © 2020-2023  润新知