#include #include constexpr int MAX_G = 301; template class LinkedList { public: NodeT* head = new NodeT(); NodeT* tail = head; NodeT* push_front(int val) { auto* node = new NodeT{.val = val}; push_front(node); return node; } void push_front(NodeT* node) { tail->next = node; tail = node; } void push_back(NodeT* node) { node->next = head->next; head->next = node; } int pop_back() { NodeT* prev_node = head->next; head->next = prev_node->next; if (tail == prev_node) { tail = head; } int val = prev_node->val; delete prev_node; return val; } NodeT* back() { return head->next; } bool empty() { return head == tail; } }; struct Node { int val = -1; Node* next = nullptr; // Node* prev = nullptr; }; struct AdvancedNode : Node { using Node::Node; int group{}; AdvancedNode* next = nullptr; LinkedList children; }; class AdvancedLinkedList : public LinkedList { public: // Node* head = new Node(); AdvancedNode* father_nodes[MAX_G] = {}; AdvancedNode* push_front(int val, int grp) { auto* node = new AdvancedNode(); node->val = val, node->group = grp; if (father_nodes[grp] == nullptr) { father_nodes[grp] = node; LinkedList::push_front(node); } else { father_nodes[grp]->children.push_front(node); } return node; } int pop_back() { if (back()->children.empty()) { father_nodes[back()->group] = nullptr; return LinkedList::pop_back(); } int current_val = back()->val; back()->val = back()->children.pop_back(); return current_val; } }; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n, groups_amount; std::vector element_groups; AdvancedLinkedList list; std::cin >> n >> groups_amount; element_groups.resize(n); for (int i = 0; i < n; i++) { std::cin >> element_groups[i]; } std::cin >> n; std::string op; int elem_id; for (int _ = 0; _ < n; _++) { std::cin >> op; if (op == "push") { std::cin >> elem_id; list.push_front(elem_id, element_groups[elem_id]); } else { std::cout << list.pop_back() << std::endl; } } return 0; }