
假设我们有一个空序列和n个需要处理的查询。查询以数组queries的格式给出,格式为{query,data}。查询可以有以下三种类型:
query = 1:将提供的数据添加到序列的末尾。
query = 2:打印序列开头的元素。然后删除该元素。
query = 3:按升序对序列进行排序。
立即学习“C++免费学习笔记(深入)”;
注意,查询类型2和3的data始终为0。
因此,如果输入是n = 9,queries = {{1, 5},{1, 4},{1, 3},{1, 2},{1, 1},{2, 0},{3, 0},{2, 0},{3, 0}},那么输出将是5和1。
每个查询后的序列如下所示:
1:{5}2:{5, 4}3:{5, 4, 3}4:{5, 4, 3, 2}5:{5, 4, 3, 2, 1}6:{4, 3, 2, 1},打印5。7:{1, 2, 3, 4}8:{2, 3, 4},打印1。9:{2, 3, 4}
要解决这个问题,我们将按照以下步骤进行:
priority_queue priqDefine one queue qfor initialize i := 0, when i < n, update (increase i by 1), do: operation := first value of queries[i] if operation is same as 1, then: x := second value of queries[i] insert x into q otherwise when operation is same as 2, then: if priq is empty, then: print first element of q delete first element from q else: print -(top element of priq) delete top element from priq otherwise when operation is same as 3, then: while (not q is empty), do: insert (-first element of q) into priq and sort delete element from q
Example
让我们来看下面的实现,以便更好地理解 −
#include using namespace std;void solve(int n, vector<pair> queries){ priority_queue priq; queue q; for(int i = 0; i < n; i++) { int operation = queries[i].first; if(operation == 1) { int x; x = queries[i].second; q.push(x); } else if(operation == 2) { if(priq.empty()) { cout << q.front() << endl; q.pop(); } else { cout << -priq.top() << endl; priq.pop(); } } else if(operation == 3) { while(!q.empty()) { priq.push(-q.front()); q.pop(); } } }}int main() { int n = 9; vector<pair> queries = {{1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {2, 0}, {3, 0}, {2, 0}, {3, 0}}; solve(n, queries); return 0;}
输入
9, {{1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {2, 0}, {3, 0}, {2, 0}, {3, 0}}
输出
51
以上就是使用C++对序列执行特定操作的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444319.html
微信扫一扫
支付宝扫一扫