首頁  >  文章  >  後端開發  >  使用C++對序列執行特定操作

使用C++對序列執行特定操作

WBOY
WBOY轉載
2023-09-03 11:49:06944瀏覽

使用C++對序列執行特定操作

假設我們有一個空序列和n個需要處理的查詢。查詢以數組queries的格式給出,格式為{query,data}。查詢可以有以下三種類型:

  • query = 1:將提供的資料加入到序列的末端。

  • query = 2:列印序列開頭的元素。然後刪除該元素。

  • query = 3:以升序對序列進行排序。

注意,查詢類型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<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;
}

輸入

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

#輸出

5
1

以上是使用C++對序列執行特定操作的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除