用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;
}