#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
struct Element{
public:
string word;
int number = 0;
Element *left = NULL;
Element *right = NULL;
Element(string word, int d):word(word){
number = d;
left = right = this;
}
};
class ListTwoCyclic{
public:
Element *link = NULL;
int size = 0;
void moveTo(bool left = true){
if(left) link = link->left;
else link = link->right;
}
void add(string word, int d, bool left = true){
Element *n = new Element(word, d);
if(size == 0)
link = n;
else{
Element *l = link->left;
Element *r = link->right;
if(left){
link->left = n;
n->right = link;
n->left = l;
l->right = n;
if(size == 1) link->right = n;
}
else{
link->right = n;
n->left = link;
n->right = r;
r->left = n;
if(size == 1) link->left = n;
}
}
++size;
}
bool rmv(){
if(size == 0) return false;
if(size == 1){
delete link;
link == NULL;
}
else{
Element *temp = link;
link = link->left;
link->right = temp->right;
link->right->left = link;
delete temp;
}
--size;
return true;
}
void show(){
if(link) cout << link->word << " " << link->number << endl;
Element *temp = link;
if(size){
for(int i = 0; i < size; ++i){
cout << temp->word << " " << temp->number << endl;
temp = temp->left;
}
}
}
};
int main()
{
ListTwoCyclic a;
int n, s, x, y, p = 0, num;
string arr, word;
cin >> n >> s;
num = s;
for(int i = 0; i < n; ++i){
cin >> word >> x;
a.add(word, x, false);
if(x == 0) p++;
}
for(int j = 0; j < p; ++j)
cin >> word; cin >> x; cin >> y;
n += p;
for(int i = 0; i < n; ++i){
if(num > 0){
for(int j = 0; j < num; ++j)
a.moveTo(true);
if(a.link->number != 0){
arr += a.link->word;
arr += " ";
num = a.link->number;
a.rmv();
}
else{
a.link->number = y;
a.add(word, x, true);
}
}
else{
num = abs(num);
for(int k = 0; k < num; ++k)
a.moveTo(false);
if(a.link->number != 0){
arr += a.link->word;
arr += " ";
num = a.link->number;
a.rmv();
}
else{
a.link->number = y;
a.add(word, x, true);
}
}
}
cout << " "
" ";
a.show();
cout << " " << arr << endl;
return 0;
}
problem jest w tym, ze to slowo gdzie było 0 nie dodaje się do wyniku.