用stl中的优先队列,一开始实在想不到用什么方法来写。百度后有看到用优先队列写的。有一种恍然大悟的感觉。想到定义结构体,在结构体中又定义了结构体的大小比较函数。一开始函数写出来没有对。从编译的提示中知道了要如何对函数定义。
#include <iostream>
#include <string>
#include <queue>
using namespace std;
#define MAX 10001
struct str{ //定义结构体
string name;
int count;
bool operator <(const struct str &a)const //结构体的大小比较函数
{
if (count>a.count)
return true;
else if ( count==a.count && name<a.name)
return true;
else
return false;
}
};
int main()
{
int num, n, i, cur, a, b;//a b用于操作
struct str s;
string opra; // 用于操作
while (cin>>num>>n)
{
priority_queue<str> q[MAX];
for (i=1; i<=num; i++)
{
cin>>cur;
while (cur--)
{
cin>>s.name>>s.count;
q[i].push(s);
}
}
while (n--)
{
cin>>opra;
if (opra=="GETOUT") // GETOUT
{
cin>>a;
cout<<q[a].top().name<<endl;
q[a].pop();
}
else if (opra=="GETON") //GETON
{
cin>>a>>s.name>>s.count;
q[a].push(s);
}
else //join
{
cin>>a>>b;
while (!q[b].empty())
{
q[a].push(q[b].top());
q[b].pop();
}
}
}
}
return 0;
}