好坑的一道题!!!wrong了三遍,才ac!
重要的时间说三遍,细节细节细节
题目链接
涉及的知识点:优先队列的插入,判空,输出,以及自定义结构体优先级(重点)
在看以下代码之前,还请自己做一遍,一定要注意时间和空间哦!!
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
struct student
{
char place[110];//一开始开到了10000,超空间了
int x;
int y;
int id;
friend bool operator < (student a,student b)
{
if(a.y==b.y) return a.id>b.id;
else return a.y>b.y;//y小的在前;
}
};
int main()
{
char order[4];//一开始用的string,超时了
priority_queue<student>s;
int k=0;
while(scanf("%s",order)!=EOF)
{
if(order[0]=='G')
{
if(s.empty())
printf("EMPTY QUEUE!\n");
else
{
printf("%s %d\n",s.top().place,s.top().x);
s.pop();
}
}
else if(order[0]=='P')
{
student note;
scanf("%s%d%d",note.place,¬e.x,¬e.y);
note.id=k++;
s.push(note);
}
}
return 0;
}
没有百度到为什么用string会超时的愿因,先记住吧,能用char 就用char吧!!
这里说一下对重载小于号进行一下解释:
//通过一个元素来确定关系;
struct student
{
int y;
friend bool operator < (student a,student b)
{
return a.y>b.y;//y小的在前面;
//可以这样理解:
//【b】【a】
//b在a的前面,a.y>b.y时返回1,所以小的在前面;
//return a.y<b.y;//y大的在前面;
}
};
//通过两个元素来确定关系;
struct student
{
int y;
int id;
friend bool operator < (student a,student b)
{
if(a.y==b.y) return a.id>b.id;//当y相同时,id小的在前面;
else return a.y>b.y;//y小的在前;//y不同时,小的在前面;
}
};
在STL里涉及到结构体时,有许多情况需要重载,上面介绍的重载小于号,还是冰山一角,自己还可以多多了解。