ホームページ  >  記事  >  バックエンド開発  >  C++ を使用してシーケンスに対して特定の操作を実行する

C++ を使用してシーケンスに対して特定の操作を実行する

WBOY
WBOY転載
2023-09-03 11:49:06944ブラウズ

C++ を使用してシーケンスに対して特定の操作を実行する

空のシーケンスと、処理する必要のある n 個のクエリがあるとします。クエリは、{query, data} 形式の配列クエリの形式で指定されます。クエリには次の 3 つのタイプがあります。

  • 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

Example

理解を深めるために、次の実装を見てください。 -

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

Input

9, {{1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {2, 0}, {3, 0}, {2, 0}, {3, 0}}

Output

5
1

以上がC++ を使用してシーケンスに対して特定の操作を実行するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。