STL之优先队列、队列、栈的使用

这里写图片描述

学习文献

推荐值★★★★★
http://www.cppblog.com/CodeStream/archive/2011/03/25/142700.html
推荐值★★★
http://www.cnblogs.com/summerRQ/articles/2470130.html

STL之优先队列priority_queue

这里写图片描述

题目大意

Tom and Jerry玩一个游戏,Tom有n个管子,每个管子都有初始的珍珠个数,Jerry可以再任意罐子里放k的整数倍个珍珠,当然可以不放,最终能使每个管子含有1,2,3,4,5,……,n个珍珠则Jerry win!否则Tom win!

解题思路

这是2014年上海全国邀请赛的题目!

其实实现起来比较简单,我们可以将所有的数扔进优先队列中(优先队列自定义优先级为最小值优先,默认的是最大值),令cnt=1,从1开始查看队列中最小值(即队首元素)是否相等,相等就比较第二位,cnt=2;如果小于,该元素+k进入队列继续循环;如果大于,说明队列中最小值都不能满足第cnt个位置的cnt值,无解,Jerry无法操作了,此时Tom获胜,如果所有位置都能满足,那么Jerry取胜!

参考代码+部分注释

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <map>
#include <vector>
#include <queue>
#include <cstring>
#include <cmath>
#include <climits>
#define eps 1e-8
using namespace std;
typedef long long ll;
const int maxx=INT_MAX;
const int maxn = 1e4+10;
int n,k;
struct cmp    //自定义优先级,默认最大值优先<
{
  bool operator()(int x,int y)
  {
      return x>y;//最小值优先
  }
};
int main()
{
 //  freopen("input.txt","r",stdin);
   priority_queue<int,vector<int>,cmp>q;//定义优先队列
   int T;cin>>T;
   while(T--){
    while(!q.empty()) q.pop();//处理每组数据之前都要清空队列queue
    int temp;
    cin>>n>>k;
    for(int i=0;i<n;i++){
        cin>>temp;
        q.push(temp);//入队
    }
    int cnt=1;
    bool ok=true;
    while(!q.empty()&&cnt<=n){
        temp=q.top();
        q.pop();
        if(temp==cnt) cnt++;
        else if(temp<cnt) q.push(temp+k);
        else {   //如果队列中最小元素不能满足第i个值i,说明Jerry此时无法操作了,Game over!
            ok=false;
            break;
        }
    }
    if(ok) puts("Jerry"); else puts("Tom");
   }
   return 0;
}
优先队列是一种特殊的队列,可以根据元素的优先级自动排序,最常见的实现方式是使用堆(heap)。以下是一个使用堆实现优先队列的示例代码: ```c++ #include <iostream> #include <vector> using namespace std; class PriorityQueue { public: PriorityQueue() {} void push(int val) { heap.push_back(val); int idx = heap.size() - 1; while (idx > 0 && heap[idx] > heap[(idx - 1) / 2]) { swap(heap[idx], heap[(idx - 1) / 2]); idx = (idx - 1) / 2; } } void pop() { int lastIdx = heap.size() - 1; swap(heap[0], heap[lastIdx]); heap.pop_back(); int idx = 0; while (2 * idx + 1 < heap.size()) { int maxChildIdx = 2 * idx + 1; if (maxChildIdx + 1 < heap.size() && heap[maxChildIdx + 1] > heap[maxChildIdx]) { maxChildIdx++; } if (heap[idx] < heap[maxChildIdx]) { swap(heap[idx], heap[maxChildIdx]); idx = maxChildIdx; } else { break; } } } int top() { return heap[0]; } bool empty() { return heap.empty(); } private: vector<int> heap; }; ``` 在这个实现,我们使用一个动态数组来存储队列的元素,然后通过堆的方式来维护元素的优先级顺序。具体来说,我们使用一个大根堆来实现优先队列,每次插入元素时,我们将其插入到堆的末尾,然后不断将其与其父节点比较,如果比父节点优先级高,则交换位置,直到找到合适的位置。删除元素时,我们将堆顶元素与最后一个元素交换位置,然后弹出最后一个元素,最后不断将堆顶元素与其子节点比较,如果比子节点优先级低,则交换位置,直到找到合适的位置。获取队列首元素时,直接返回堆顶元素即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值