以leetcode 1081题为例,https://leetcode.cn/problems/number-of-orders-in-the-backlog/
class Solution { public: int getNumberOfBacklogOrders(vector<vector<int>>& orders) { // 新增sell订单,找buy的大于sell的,找buy最大值 // 新增buy订单,找sell的小于buy的,找sell最小值 priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> sell; // [price, amount] priority_queue<pair<int, int>, vector<pair<int, int>>, less<pair<int, int>>> buy; for (auto od : orders) { if (od[2] == 0) { // buy while (!sell.empty() && od[1] > 0 && sell.top().first <= od[0]) { if (od[1] >= sell.top().second) { od[1] -= sell.top().second; sell.pop(); } else { int price = sell.top().first; int amount = sell.top().second-od[1]; sell.pop(); sell.push({price, amount}); od[1] = 0; } } if (od[1] != 0) { buy.push({od[0], od[1]}); } } else { // sell while (!buy.empty() && od[1] > 0 && buy.top().first >= od[0]) { if (od[1] >= buy.top().second) { od[1] -= buy.top().second; buy.pop(); } else { int price = buy.top().first; int amount = buy.top().second-od[1]; buy.pop(); buy.push({price, amount}); od[1] = 0; } } if (od[1] != 0) { sell.push({od[0], od[1]}); } } } int MOD = 1000000007; int total = 0; while (!buy.empty()) { total = (total + buy.top().second) % MOD; buy.pop(); } while (!sell.empty()) { total = (total + sell.top().second) % MOD; sell.pop(); } return total; } };
标签:sell,queue,buy,int,top,od,C++,priority,second From: https://www.cnblogs.com/roadwide/p/17019771.html