我要吐槽下,被自己坑了两个多小时,也说明自己测试不仔细!仅仅在输出xxx is so poor少了一点,一点呀!一个点就等于我的两个小时T_T,都没天理了。言归正传,说说解题思路。1 经过本人的不懈努力,经验之谈,不要用c++的cout做输出,很容易超时!用c的printf2 这题数据量应该很大,用传统的排序方法是过不了滴,在这里要用堆,大根堆和小根堆小解:小根堆简单的说就是一个数组里面总是最小的那个排在首位,大根堆则相反,总是最大的排在最前。所以在这里我就偷懒的使用了优先队列。3 保持大小根堆的平衡,小根堆的大小总是等于大根堆或者比大根堆大1,所以在输出的时候,就直接输出小根堆的头部元素就是答案了。
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <queue>
using namespace std;
struct user {
user(){}
user(char n[], int c) {
strcpy(name, n);
cnt = c;
}
char name[15];
int cnt;
};
class mincmp {
public:
bool operator()(const user a,const user b) const
{
return a.cnt > b.cnt;
}
};
class maxcmp {
public:
bool operator()(const user& a,const user& b) const
{
return a.cnt < b.cnt;
}
};
priority_queue<user, vector<user>, maxcmp > maxq;
priority_queue<user, vector<user>, mincmp> minq;
void insert(user u)
{
if (minq.empty())
minq.push(u);
else if (maxq.size() >= minq.size())
{
user tmp = maxq.top();
if (u.cnt < tmp.cnt)
{
maxq.pop();
maxq.push(u);
u = tmp;
}
minq.push(u);
}
else
{
user tmp = minq.top();
if (u.cnt > tmp.cnt)
{
minq.pop();
minq.push(u);
u = tmp;
}
maxq.push(u);
}
}
int main()
{
int t;
scanf("%d",&t);
bool f = false;
char cmd[10];
while (t--) {
if (f)
printf("\n");
f = true;
int size = 0;
while (true) {
scanf("%s",cmd);
if (strcmp(cmd, "Add") == 0){
char name[15];
int procnt;
scanf("%s %d",name, &procnt);
user nu(name, procnt);
insert(nu);
++size;
}
else if (strcmp(cmd,"Query") == 0) {
if ((size & 1) == 0)
printf("No one!\n");
else
printf("%s\n",minq.top().name);
}
else
break;
}
if ((size & 1) == 0)
printf("Happy BG meeting!!\n");
else
printf("%s is so poor.\n", minq.top().name);
while (!minq.empty())
minq.pop();
while (!maxq.empty())
maxq.pop();
}
return 0;
}