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\n",ans);
    }
    
    return 0;
}

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

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

  q.pop();

}

猜你喜欢

转载自www.cnblogs.com/visper/p/10098931.html