好坑的一道題!!!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裡涉及到結構體時,有許多情況需要重載,上面介紹的重載小于号,還是冰山一角,自己還可以多多了解。
轉載的一篇很好的文章