# C++ to perform certain operations on a sequence

Suppose, we are given an empty sequence and n queries that we have to process. The queries are given in the array queries and they are in the format {query, data}. The queries can be of the three following types−

• query = 1: Add the supplied data to the end of the sequence.

• query = 2: Print the element at the beginning of the sequence. After that delete the element.

• query = 3: Sort the sequence in ascending order.

Note that, query types 2 and 3 always have data = 0.

So, if the input is like 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 given below −

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

To solve this, 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

## Example

Let us see the following implementation to get 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;
}

## Input

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


## Output

5
1