学习文献
推荐值★★★★★
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;
}