zoukankan      html  css  js  c++  java
  • 2017级算法第二次上机-B.女娲加农炮

    这道题本质上还是最经典的优先队列的使用的例题:合并果子。

    借用这道题总结复习一下优先队列。

    优先队列的头文件:<queue>

    升序队列
    priority_queue <int,vector<int>,greater<int> > q;
    降序队列
    priority_queue <int,vector<int>,less<int> >q;

    注意优先队列有升序版本的 也有降序版本的

    接下来说明一下优先队列常用的方法:

    q.empty() 如果队列为空,则返回true,否则返回false 注意这个函数的返回值是bool类型的

    q.size() 返回队列中元素的个数 

    q.pop() 删除队首元素 但不返回其值 

    q.top() 返回具有最高优先级的元素值 但不删除该元素

    q.push(item) 在基于优先级的适当位置插入新元素

    二维元素的合并果子:

    #include <algorithm>
    #include <iostream>
    #include <queue>
    
    using namespace std;
    priority_queue <int , vector<int> , greater<int> > p;//升序队列
    priority_queue <int , vector<int> , less<int> > q;//降序队列
    
    int main(){
        
        int n,num,i,x,y;
        long long ans=0;
        while(~scanf("%d",&n)){
            
            while(!p.empty()) p.pop();
            
            for(i=1;i<=n;i++){
                scanf("%d",&num);
                p.push(num);
            }
            ans=0;
            for(i=1;i<n;i++){
                x = p.top();p.pop();
                y = p.top();p.pop();
                ans +=x+y;
                p.push(x+y);
            }
            printf("%lld
    ",ans);
        }
        
        return 0;
    }

    有一些是小的trick 比如在使用优先队列之前要清空(clear)

    while(q.empty() == false ){

      q.pop();

    }

  • 相关阅读:
    PLSQL查询显示乱码或者问号
    Sonar 扫描C#代码 排除文件
    C# 短日期转换为DateTime
    电脑远程连接不上或者ip的地址一直是169.254
    C#导出CSV或者EXCEL文件转换文本
    Oracle 计算两个日期相差天时分秒
    Linux 做网关
    Python 内置函数
    Python Fileinput 模块
    Python-2.7 配置 tab 自动补全功能
  • 原文地址:https://www.cnblogs.com/visper/p/10098931.html
Copyright © 2011-2022 走看看