C++ 在序列上执行特定操作


假设我们给定一个空序列和 n 个查询,我们需要处理这些查询。这些查询以数组查询形式给出,并采用 {查询,数据} 的格式。查询可以是以下三种类型之一:

  • query = 1:将提供的数据添加到序列末尾。

  • query = 2:打印序列开头元素。之后删除元素。

  • query = 3:按升序对序列进行排序。

请注意,查询类型 2 和 3 始终具有数据 = 0。

因此,如果输入为 n = 9,查询 = {{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<int> priq
Define one queue q
for 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

示例

让我们看看以下实现,以获得更好的理解:

#include <bits/stdc++.h>
using namespace std;

void solve(int n, vector<pair<int, int>> queries){
   priority_queue<int> priq;
   queue<int> 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<int, int>> 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}}

输出

5
1

更新于:02-Mar-2022

338 浏览量

职业,开启新航程

通过完成课程取得认证

开始
广告
© . All rights reserved.