Home > Article > Backend Development > Perform specific operations on sequences using C++
Suppose we have an empty sequence and n queries that need to be processed. Queries are given in the form of array queries in the format {query, data}. Queries can be of the following three types:
query = 1: Appends the provided data to the end of the sequence.
query = 2: Print the element at the beginning of the sequence. Then delete the element.
query = 3: Sort the sequence in ascending order.
Note that the data of query types 2 and 3 is always 0.
So if the input is n = 9, queries = {{1, 5}, {1, 4}, {1, 3}, {1, 2}, {1, 1}, {2 , 0}, {3, 0}, {2, 0}, {3, 0}}, then the output will be 5 and 1.
The sequence after each query is as follows:
To solve this problem we will follow these steps:
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
Let us look at the following implementation for better understanding −
#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
The above is the detailed content of Perform specific operations on sequences using C++. For more information, please follow other related articles on the PHP Chinese website!