Computer >> Máy Tính >  >> Lập trình >> C ++

C ++ để thực hiện các hoạt động nhất định trên một chuỗi

Giả sử, chúng ta được cung cấp một dãy trống và n truy vấn mà chúng ta phải xử lý. Các truy vấn được đưa ra trong các truy vấn mảng và chúng có định dạng {query, data}. Các truy vấn có thể thuộc ba loại sau đây−

  • query =1:Thêm dữ liệu được cung cấp vào cuối chuỗi.

  • query =2:In phần tử ở đầu dãy. Sau đó, xóa phần tử.

  • query =3:Sắp xếp chuỗi theo thứ tự tăng dần.

Lưu ý rằng, loại truy vấn 2 và 3 luôn có dữ liệu =0.

Vì vậy, nếu đầu vào là n =9, các truy vấn ={{1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {2, 0}, {3, 0}, {2, 0}, {3, 0}}, thì đầu ra sẽ là 5 và 1.

Trình tự sau mỗi truy vấn được đưa ra bên dưới -

  • 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}, Bản in 5.
  • 7:{1, 2, 3, 4}
  • 8:{2, 3, 4}, Bản in 1.
  • 9:{2, 3, 4}

Để giải quyết vấn đề này, chúng tôi sẽ làm theo các bước sau -

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

Ví dụ

Hãy cùng chúng tôi xem cách triển khai sau để hiểu rõ hơn -

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

Đầu vào

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

Đầu ra

5
1