出处:https://blog.csdn.net/zju2016/article/details/75005098
题目链接:https://vjudge.net/contest/231030#problem/N
#include<iostream>
#include<vector>
#include<string>
#include<type_traits>
#include<sstream>
#include<tuple>
#include<bitset>
#include<regex>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
map<int, set<int>> Buy;//映射:购买价格到购买的指令编号
map<int, int> Buy_total;//映射:购买价格到购买总量
map<int, set<int>> Sell;//映射:卖的价格到卖的指令编号
map<int, int> Sell_total;//映射:贩卖价格到贩卖总量
typedef struct command{
string com;
int price, amount;
int id;
}command;
vector<command> Com;//存储指令
void Deal(int flag){//处理"TRADE"
while (!Buy.empty()&&!Sell.empty()){
if (Buy.rbegin()->first>=Sell.begin()->first){
set<int>& v1 = Buy.rbegin()->second;
set<int>& v2 = Sell.begin()->second;
int number1 = *v1.begin();
int number2 = *v2.begin();
int size = min(Com[number1].amount,Com[number2].amount);
Com[number1].amount -= size;
Com[number2].amount -= size;
Buy_total[Com[number1].price] -= size;
Sell_total[Com[number2].price] -= size;
cout << "TRADE " << size << " " << (flag ? Com[number1].price : Com[number2].price)<<endl;
if (Com[number1].amount == 0) v1.erase(number1);
if (Com[number2].amount == 0) v2.erase(number2);
if (Buy_total[Com[number1].price] == 0) Buy_total.erase(Com[number1].price);
if (Sell_total[Com[number2].price] == 0) Sell_total.erase(Com[number2].price);
if (v1.size() == 0) Buy.erase(Com[number1].price);
if (v2.size() == 0) Sell.erase(Com[number2].price);
}
else{
return;
}
}
}
void Print(){//处理"QUOTE"
cout << "QUOTE ";
if (Buy_total.size() == 0) cout << "0 0 - ";
else{
cout<<Buy_total.rbegin()->second<< " " << Buy_total.rbegin()->first << " - ";
}
if (Sell_total.size() == 0) cout << "0 99999" << endl;
else cout <<Sell_total.begin()->second << " " << Sell_total.begin()->first << endl;
}
int main(){
int Case = 0;
int n;
while (cin >> n){
Buy.clear(); Buy_total.clear();
Sell.clear(); Sell_total.clear();
Com.clear();
if (Case++) cout << endl;
for (int i = 0; i < n; i++){
command temp;
cin >> temp.com;
if (temp.com == "BUY"){
cin >> temp.amount >> temp.price;
Buy[temp.price].insert(i);
Buy_total[temp.price] += temp.amount;
Com.push_back(temp);
Deal(0);
}
else if (temp.com=="SELL"){
cin >> temp.amount >> temp.price;
Sell[temp.price].insert(i);
Sell_total[temp.price] += temp.amount;
Com.push_back(temp);
Deal(1);
}
else{
int id;
cin >> id;
id--;
temp.id = id;
Com.push_back(temp);
int price = Com[id].price;
if (Com[id].com == "BUY"){
Buy[price].erase(id);
Buy_total[price] -= Com[id].amount;
if (Buy[price].empty()) Buy.erase(price);
if (Buy_total[price] == 0) Buy_total.erase(price);
Com[id].amount = 0;
}
if(Com[id].com=="SELL"){
Sell[price].erase(id);
Sell_total[price] -= Com[id].amount;
if (Sell[price].empty()) Sell.erase(price);
if (Sell_total[price] == 0) Sell_total.erase(price);
Com[id].amount = 0;
}
}
Print();
}
}
return 0;
}