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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值