In this task you need to process a set of stock exchange orders and use them to create order book.

An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price p_{i}, direction d_{i} — buy or sell, and integer q_{i}. This means that the participant is ready to buy or sell q_{i} stocks at price p_{i} for one stock. A value q_{i} is also known as a volume of an order.

All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.

An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.

An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.

You are given n stock exhange orders. Your task is to print order book of depth s for these orders.


-----Input-----

The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth.

Next n lines contains a letter d_{i} (either 'B' or 'S'), an integer p_{i} (0 ≤ p_{i} ≤ 10^5) and an integer q_{i} (1 ≤ q_{i} ≤ 10^4) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.


-----Output-----

Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.


-----Examples-----
Input
6 2
B 10 3
S 50 2
S 40 1
S 50 6
B 20 4
B 25 10

Output
S 50 8
S 40 1
B 25 10
B 20 4



-----Note-----

Denote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.

You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.

Source: codeforces | Difficulty: EASY
Tags: Sorting

Data structures

Implementation

Greedy algorithms


Solutions:
(n, s) = map(int, input().split())
buy = {}
sell = {}
for i in range(n):
	r = input().split()
	d = r[0]
	p = int(r[1])
	v = int(r[2])
	if d == 'S':
		sell[p] = sell.get(p, 0) + v
	else:
		buy[p] = buy.get(p, 0) + v
for order in sorted(sell.items(), reverse=True)[-s:]:
	print('S %s %s' % (order[0], order[1]))
for order in sorted(buy.items(), reverse=True)[:s]:
	print('B %s %s' % (order[0], order[1]))


(n, s) = list(map(int, input().split()))
buyorder = []
sellorder = []
for i in range(n):
	line = input()
	order = line.split()
	order[1] = int(order[1])
	order[2] = int(order[2])
	if order[0] == 'B':
		for m in buyorder:
			if m[1] == order[1]:
				m[2] += order[2]
				break
		else:
			buyorder.append(order)
	else:
		for m in sellorder:
			if m[1] == order[1]:
				m[2] += order[2]
				break
		else:
			sellorder.append(order)
buyorder.sort(key=lambda data: data[1], reverse=True)
sellorder.sort(key=lambda data: data[1], reverse=False)
if len(sellorder) < s:
	sellorder.sort(key=lambda data: data[1], reverse=True)
	for i in sellorder:
		print(i[0], i[1], i[2])
else:
	newsell = []
	for i in range(s):
		newsell.append(sellorder[i])
	newsell.sort(key=lambda data: data[1], reverse=True)
	for i in range(s):
		print(newsell[i][0], newsell[i][1], newsell[i][2])
if len(buyorder) < s:
	for i in buyorder:
		print(i[0], i[1], i[2])
else:
	for i in range(s):
		print(buyorder[i][0], buyorder[i][1], buyorder[i][2])


(n, s) = list(map(int, input().split()))
buy = {}
sale = {}
for i in range(n):
	cur = input().split()
	p = int(cur[1])
	q = int(cur[2])
	if cur[0] == 'B':
		if p in buy:
			buy[p] += q
		else:
			buy[p] = q
	elif p in sale:
		sale[p] += q
	else:
		sale[p] = q
items = list(sale.items())
items.sort()
items = items[:s]
items.reverse()
for i in items:
	print('S', i[0], i[1])
items = list(buy.items())
items.sort()
items.reverse()
c = 0
for i in items:
	if c == s:
		break
	print('B', i[0], i[1])
	c += 1


from sys import argv
from collections import defaultdict
import sys

def convert(line):
	ret = []
	for e in line:
		try:
			ret.append(int(e))
		except:
			ret.append(e)
	return ret

def reader():
	for line in sys.stdin:
		yield convert(line.strip().split(' '))

def main():
	r = reader()
	(n, m) = next(r)
	sell = defaultdict(int)
	buy = defaultdict(int)
	for (transaction, price, quantity) in r:
		if transaction == 'B':
			buy[price] += quantity
		if transaction == 'S':
			sell[price] += quantity
	sell = sorted(sell.items(), key=lambda x: x[0], reverse=True)
	buy = sorted(buy.items(), key=lambda x: x[0], reverse=True)
	for (p, q) in sell[-m:]:
		print('S %d %d' % (p, q))
	for (p, q) in buy[:m]:
		print('B %d %d' % (p, q))
main()


(n, s) = map(int, input().split())
buy = {}
sell = {}
for i in range(n):
	a = input().split()
	a[1] = int(a[1])
	a[2] = int(a[2])
	if a[0] == 'B':
		buy[a[1]] = buy.get(a[1], 0) + a[2]
	else:
		sell[a[1]] = sell.get(a[1], 0) + a[2]
buy = list(buy.items())
sell = list(sell.items())
sell.sort()
buy.sort()
sell = sell[:s]
buy = buy[-s:]
sell.reverse()
buy.reverse()
for i in sell:
	print('S', i[0], i[1])
for i in buy:
	print('B', i[0], i[1])


import math
from decimal import *
getcontext().prec = 30
(n, s) = map(int, input().split())
buy = {}
sell = {}
for i in range(n):
	(d, p, q) = input().split()
	p = int(p)
	q = int(q)
	if d == 'B':
		if p not in buy:
			buy[p] = 0
		buy[p] += q
	else:
		if p not in sell:
			sell[p] = 0
		sell[p] += q
x = sorted(buy.items(), reverse=True)
y = sorted(sell.items())
sell = dict(y)
ans1 = list(sell.values())
ans2 = list(sell.keys())
for i in range(min(len(sell) - 1, s - 1), -1, -1):
	print('S {} {}'.format(ans2[i], ans1[i]))
buy = dict(x)
ans1 = list(buy.values())
ans2 = list(buy.keys())
for i in range(min(len(buy), s)):
	print('B {} {}'.format(ans2[i], ans1[i]))


(n, s) = map(int, input().split())
buys = dict()
sell = dict()
for _ in range(n):
	f = input().split()
	if f[0] == 'B':
		buys[int(f[1])] = buys.get(int(f[1]), 0) + int(f[2])
	else:
		sell[int(f[1])] = sell.get(int(f[1]), 0) + int(f[2])
bres = sorted(buys.keys(), reverse=True)
sres = sorted(sell.keys())
if bres:
	bs = bres[min(s - 1, len(bres) - 1)]
if sres:
	ss = sres[min(s - 1, len(sres) - 1)]
	for key in sorted(sell.keys(), reverse=True):
		if key <= ss:
			print('S', key, sell[key])
if bres:
	bs = bres[min(s - 1, len(bres) - 1)]
	for key in sorted(buys.keys(), reverse=True):
		if key >= bs:
			print('B', key, buys[key])


(n, s) = input().split()
(n, s) = (int(n), int(s))
buy_dict = {}
sell_dict = {}
for i in range(n):
	(chtype, pi, di) = input().split()
	pi = int(pi)
	di = int(di)
	if chtype == 'B':
		buy_dict[pi] = buy_dict.get(pi, 0) + di
	else:
		sell_dict[pi] = sell_dict.get(pi, 0) + di
buy_list = sorted(buy_dict.items(), reverse=True)[:s]
sell_list = reversed(sorted(sell_dict.items())[:s])
for (pi, qi) in sell_list:
	print('S', pi, qi)
for (pi, qi) in buy_list:
	print('B', pi, qi)


(n, s) = list(map(int, input().split()))
orders = {}
for _ in range(n):
	(t, p, v) = input().split()
	(p, v) = (int(p), int(v))
	if orders.get((t, p)) is not None:
		orders[t, p] += v
	else:
		orders[t, p] = v
buys = []
sells = []
for (key, value) in orders.items():
	if key[0] == 'S':
		sells.append((key[1], value))
	else:
		buys.append((key[1], value))
sells.sort(key=lambda x: x[0], reverse=True)
buys.sort(key=lambda x: x[0], reverse=True)
s_n = len(sells)
for sell in sells[max(s_n - s, 0):]:
	print(f'S {sell[0]} {sell[1]}')
for i in range(len(buys)):
	if i == s:
		break
	print(f'B {buys[i][0]} {buys[i][1]}')


from collections import defaultdict
(n, s) = [int(s) for s in input().split()]
buyq = defaultdict(int)
selq = defaultdict(int)
sq = 0
bq = 0
for i in range(n):
	(d, p, q) = input().split()
	p = int(p)
	q = int(q)
	if d == 'B':
		buyq[p] += q
	else:
		selq[p] += q
a = sorted(selq.keys())
for i in a[min(s, len(selq)) - 1::-1]:
	print('S', i, selq[i])
b = sorted(buyq.keys())
for i in b[::-1][:min(s, len(buyq))]:
	print('B', i, buyq[i])


(n, s) = map(int, input().split())
buy = {}
sell = {}
for _ in range(n):
	temp = list(map(str, input().split()))
	if temp[0] == 'B':
		buy[int(temp[1])] = buy.get(int(temp[1]), 0) + int(temp[2])
	else:
		sell[int(temp[1])] = sell.get(int(temp[1]), 0) + int(temp[2])
for (key, value) in reversed(sorted(sell.items())[:s]):
	print('S', key, value)
for (key, value) in sorted(buy.items(), reverse=True)[:s]:
	print('B', key, value)


(n, s) = map(int, input().split())
buying = []
selling = []
for o in range(n):
	ord = input().split()
	if ord[0] == 'B':
		buying.append([int(ord[1]), int(ord[2]), ord[0]])
	else:
		selling.append([int(ord[1]), int(ord[2]), ord[0]])
pricesbuy = {}
pricessell = {}
for x in buying:
	pricesbuy[x[0]] = 0
for y in selling:
	pricessell[y[0]] = 0
for x in buying:
	pricesbuy[x[0]] += x[1]
for y in selling:
	pricessell[y[0]] += y[1]
buyfin = []
sellfin = []
for k in pricesbuy:
	buyfin.append([k, pricesbuy[k]])
for k in pricessell:
	sellfin.append([k, pricessell[k]])
buyfin.sort(reverse=True)
sellfin.sort()
buyfinfin = []
sellfinfin = []
for x in range(min(len(sellfin), s)):
	sellfinfin.append(sellfin[x])
for x in range(min(len(buyfin), s)):
	buyfinfin.append(buyfin[x])
buyfinfin.sort(reverse=True)
sellfinfin.sort(reverse=True)
for x in range(min(len(sellfinfin), s)):
	print('S' + ' ' + str(sellfinfin[x][0]) + ' ' + str(sellfinfin[x][1]))
for x in range(min(len(buyfinfin), s)):
	print('B' + ' ' + str(buyfinfin[x][0]) + ' ' + str(abs(buyfinfin[x][1])))


(n, s) = input().split()
(n, s) = (int(n), int(s))
dic = {}
while n > 0:
	listOfInput = input().split()
	key = ' '.join(listOfInput[:-1])
	value = listOfInput[-1]
	if key in dic:
		dic[key] += int(value)
	else:
		dic[key] = int(value)
	n -= 1
listOfSells = sorted([int(key.split()[1]) for key in dic if key.split()[0] == 'S'])[:s]
listOfBuys = sorted([int(key.split()[1]) for key in dic if key.split()[0] == 'B'])
for i in range(s):
	if listOfSells:
		value = listOfSells.pop()
		key = 'S ' + str(value)
		print('S ' + str(value) + ' ' + str(dic[key]))
	else:
		pass
for i in range(s):
	if listOfBuys:
		value = listOfBuys.pop()
		key = 'B ' + str(value)
		print('B ' + str(value) + ' ' + str(dic[key]))
	else:
		pass


import operator
(n, s) = list(map(int, input().split()))
orders = []
for i in range(n):
	orders.append(tuple(map(str, input().split())))
aggr = {}
for order in orders:
	key = (order[0][0], int(order[1]))
	if key not in aggr:
		aggr[key] = 0
	aggr[key] += int(order[2])
books = {'B': [], 'S': []}
for key in aggr:
	book = books[key[0]]
	volume = aggr[key]
	book.append((key[0], key[1], volume))
for k in books:
	books[k] = list(reversed(sorted(books[k], key=operator.itemgetter(1))))
lenB = len(books['S'])
for i in range(min(lenB, s)):
	order = books['S'][max(0, lenB - s) + i]
	print('S %d %d' % (order[1], order[2]))
for i in range(min(len(books['B']), s)):
	order = books['B'][i]
	print('B %d %d' % (order[1], order[2]))


(n, s) = map(int, input().split())
buy = dict()
sell = dict()
for i in range(n):
	(d, p, q) = map(str, input().split())
	p = int(p)
	q = int(q)
	if d == 'B':
		if p in buy:
			buy[p] += q
		else:
			buy[p] = q
	elif p in sell:
		sell[p] += q
	else:
		sell[p] = q
bk = list(buy.keys())
bv = list(buy.values())
bl = list(zip(bk, bv))
sk = list(sell.keys())
sv = list(sell.values())
sl = list(zip(sk, sv))
bl.sort(reverse=True)
sl.sort()
bb = len(bl)
ss = len(sl)
if s > ss:
	sl.sort(reverse=True)
	for i in range(ss):
		print('S', sl[i][0], sl[i][1])
else:
	sl.sort()
	for i in range(s - 1, -1, -1):
		print('S', sl[i][0], sl[i][1])
if s > bb:
	for i in range(bb):
		print('B', bl[i][0], bl[i][1])
else:
	for i in range(s):
		print('B', bl[i][0], bl[i][1])


(n, m) = map(int, input().split())
zay = []
zay_fin_B = []
zay_fin_S = []
for i in range(n):
	zay.append(list(input().split()))
	zay[-1][1] = int(zay[-1][1])
	zay[-1][2] = int(zay[-1][2])
for i in range(n):
	if zay[i] != None:
		zay_time = zay[i]
	for j in range(i + 1, n):
		if zay[i] != None and zay[j] != None and (zay[i][0] == zay[j][0]) and (zay[i][1] == zay[j][1]):
			zay_time[2] += zay[j][2]
			zay[j] = None
	if zay[i] != None:
		if zay_time[0] == 'B':
			zay_fin_B.append(zay_time)
		else:
			zay_fin_S.append(zay_time)
		zay[i] = None
zay_fin_S.sort()
m_s = 0
ans_S = []
for i in zay_fin_S:
	if m_s < m:
		ans_S.append(i)
		m_s += 1
ans_S.reverse()
zay_fin_B.sort(reverse=True)
m_b = 0
ans_B = []
for i in zay_fin_B:
	if m_b < m:
		ans_B.append(i)
		m_b += 1
for i in ans_S:
	print(*i)
for i in ans_B:
	print(*i)


n = [int(i) for i in input().split()]
buy = []
buyP = []
sell = []
sellP = []
for i in range(n[0]):
	l = input().split()
	l[1] = int(l[1])
	l[2] = int(l[2])
	if l[0] == 'B':
		l.pop(0)
		buy.append(l)
		buyP.append([l[0]])
	else:
		l.pop(0)
		sell.append(l)
		sellP.append([l[0]])
for i in range(len(buyP) - 1, -1, -1):
	if buyP.count(buyP[i]) > 1:
		buyP.pop(i)
for i in range(len(sellP) - 1, -1, -1):
	if sellP.count(sellP[i]) > 1:
		sellP.pop(i)
buyP.sort()
buyP.reverse()
sellP.sort()
for i in range(len(sellP)):
	sellP[i].append(0)
	sellP[i].append(0)
	for j in sell:
		if sellP[i][0] == j[0]:
			sellP[i][1] = 'S'
			sellP[i][2] += j[1]
for z in range(min(n[1], len(sellP)) - 1, -1, -1):
	print('S ' + str(sellP[z][0]) + ' ' + str(sellP[z][2]))
for i in range(len(buyP)):
	buyP[i].append(0)
	buyP[i].append(0)
	for j in buy:
		if buyP[i][0] == j[0]:
			buyP[i][1] = 'B'
			buyP[i][2] += j[1]
for z in range(min(n[1], len(buyP))):
	print('B ' + str(buyP[z][0]) + ' ' + str(buyP[z][2]))


(n, s2) = map(int, input().split())
b = {}
s = {}
b1 = set()
s1 = set()
for i in range(n):
	v = list(map(str, input().split()))
	if v[0] == 'B':
		if v[1] in b1:
			b[v[1]] += int(v[2])
		else:
			b[v[1]] = int(v[2])
			b1.add(v[1])
	if v[0] == 'S':
		if v[1] in s1:
			s[v[1]] += int(v[2])
		else:
			s[v[1]] = int(v[2])
			s1.add(v[1])
ansb = []
anss = []
for (i, j) in b.items():
	ansb.append((int(i), int(j)))
ansb.sort(reverse=True)
for (i, j) in s.items():
	anss.append((int(i), int(j)))
anss.sort()
k = len(ansb)
p = len(anss)
i = 0
j = min(s2 - 1, p - 1)
s1 = s2
while s1 > 0 and p > 0:
	print('S', anss[j][0], anss[j][1])
	j -= 1
	s1 -= 1
	p -= 1
while s2 > 0 and k > 0:
	print('B', ansb[i][0], ansb[i][1])
	k -= 1
	s2 -= 1
	i += 1


(n, s) = [int(x) for x in input().split()]
ordenes = {}
for i in range(n):
	(d, p, q) = input().split()
	head = d + ' ' + p
	(p, q) = (int(p), int(q))
	if head not in ordenes:
		ordenes[head] = 0
	ordenes[head] += q
ventas = {}
compras = {}
for i in ordenes:
	if i[0] == 'B':
		compras[int(i[2:])] = str(ordenes[i])
	else:
		ventas[int(i[2:])] = str(ordenes[i])
listacompras = list(compras.keys())
listaventas = list(ventas.keys())
listacompras.sort(reverse=True)
listaventas.sort(reverse=True)
for i in range(-s, 0):
	if i < -len(ventas):
		continue
	print('S ' + str(listaventas[i]) + ' ' + str(ventas[listaventas[i]]))
for i in range(s):
	if i >= len(compras):
		break
	print('B ' + str(listacompras[i]) + ' ' + str(compras[listacompras[i]]))


import sys
from math import gcd, sqrt
from typing import DefaultDict
sys.setrecursionlimit(10 ** 5)
inf = float('inf')
en = lambda x: list(enumerate(x))
ii = lambda : int(input())
r = lambda : map(int, input().split())
rr = lambda : list(r())
(n, k) = r()
arr = DefaultDict(lambda : 0)
brr = DefaultDict(lambda : 0)
for _ in ' ' * n:
	(a, b, c) = input().split()
	c = int(c)
	b = int(b)
	if a == 'S':
		arr[b] += c
	else:
		brr[b] += c
for i in sorted(arr.keys())[:k][::-1]:
	print('S', i, arr[i])
for i in sorted(brr.keys(), reverse=1)[:k]:
	print('B', i, brr[i])


(amount, deep) = map(int, input().split())
deep_copy = deep
buy_list = []
sell_list = []
counter_1 = 0
while amount != 0:
	(direction, price, amount_pos) = map(str, input().split())
	contol_list = [direction, int(price), int(amount_pos)]
	if direction == 'B':
		buy_list.append(contol_list)
	else:
		sell_list.append(contol_list)
	amount -= 1
buy_list.sort()
sell_list.sort()
while counter_1 < len(buy_list) - 1:
	if buy_list[counter_1][1] == buy_list[counter_1 + 1][1]:
		buy_list[counter_1][2] += buy_list[counter_1 + 1][2]
		del buy_list[counter_1 + 1]
	else:
		counter_1 += 1
counter_1 = 0
while counter_1 < len(sell_list) - 1:
	if sell_list[counter_1][1] == sell_list[counter_1 + 1][1]:
		sell_list[counter_1][2] += sell_list[counter_1 + 1][2]
		del sell_list[counter_1 + 1]
	else:
		counter_1 += 1
buy_list.reverse()
b = []
for index in range(min(deep, len(sell_list))):
	b.append(sell_list[index])
b.reverse()
for index in range(len(b)):
	print(*b[index])
for index in range(min(deep, len(buy_list))):
	print(*buy_list[index])


(n, deaph) = map(int, input().split())
buy = [0] * (10 ** 5 + 1)
sell = [0] * (10 ** 5 + 1)
for i in range(n):
	s = input()
	t = s[0]
	(c, v) = map(int, s[2:].split())
	if t == 'B':
		buy[c] += v
	elif t == 'S':
		sell[c] += v
ans_sell = []
cnt = 0
i = 0
while cnt < deaph and i < len(sell):
	if sell[i] != 0:
		ans_sell.append((i, sell[i]))
		cnt += 1
	i += 1
for i in range(len(ans_sell) - 1, 0 - 1, -1):
	print('S', ans_sell[i][0], ans_sell[i][1])
cnt = 0
i = len(buy) - 1
while cnt < deaph and i >= 0:
	if buy[i] != 0:
		print('B', i, buy[i])
		cnt += 1
	i -= 1


R = lambda : list(map(int, input().split()))
from collections import defaultdict
(mps, mpb) = (defaultdict(lambda : 0), defaultdict(lambda : 0))
(n, m) = R()
for _ in range(n):
	s = input().split()
	t = s[0]
	(x, y) = (int(s[1]), int(s[2]))
	if t == 'S':
		mps[x] += y
	elif t == 'B':
		mpb[x] += y
ls = sorted(list(mps.items()), key=lambda x: x[0])
lb = sorted(list(mpb.items()), key=lambda x: x[0], reverse=True)
for (x, y) in sorted(ls[:m], reverse=True):
	print('S', x, y)
for (x, y) in lb[:m]:
	print('B', x, y)


def main():
	(n, s) = map(int, input().split())
	tot = {'S': {}, 'B': {}}
	for _ in range(n):
		tmp = input().split()
		(t, p, q) = (tot[tmp[0]], int(tmp[1]), int(tmp[2]))
		t[p] = t.get(p, 0) + q
	for c in ('S', 'B'):
		t = tot[c]
		pp = sorted(t.keys(), reverse=True)
		for p in pp[-s:] if c == 'S' else pp[:s]:
			print(c, p, t[p])
main()


def search(a, key):
	for i in range(len(a)):
		if key == a[i].price:
			return i
	return -1

def insert_max(a, key):
	size = len(a)
	i = 0
	while i < size:
		if key.price > a[i].price:
			break
		i += 1
	for j in reversed(range(i, size - 1)):
		a[j + 1] = a[j]
	if i != size:
		a[i] = key

def insert_min(a, key):
	size = len(a)
	i = 0
	while i < size:
		if key.price < a[i].price:
			break
		i += 1
	for j in reversed(range(i, size - 1)):
		a[j + 1] = a[j]
	if i != size:
		a[i] = key

class Buy:

	def __init__(self, price, vol):
		self.price = price
		self.vol = vol

class Sell:

	def __init__(self, price, vol):
		self.price = price
		self.vol = vol
(n, s) = map(int, input().split())
buy = []
sell = []
best_buy = s * [Sell(-1, 0)]
best_sell = s * [Sell(100001, 0)]
cb = 0
cs = 0
for i in range(n):
	(d, p, v) = input().split()
	price = int(p)
	vol = int(v)
	if d == 'B':
		ind = search(buy, price)
		if ind == -1:
			obj = Buy(price, vol)
			buy.append(obj)
			cb += 1
			insert_max(best_buy, obj)
		else:
			buy[ind].vol += vol
	else:
		ind = search(sell, price)
		if ind == -1:
			obj = Sell(price, vol)
			sell.append(obj)
			cs += 1
			insert_min(best_sell, obj)
		else:
			sell[ind].vol += vol
if cb > s:
	cb = s
if cs > s:
	cs = s
for i in reversed(range(cs)):
	print('S' + ' ' + str(best_sell[i].price) + ' ' + str(best_sell[i].vol))
for i in range(cb):
	print('B' + ' ' + str(best_buy[i].price) + ' ' + str(best_buy[i].vol))


from sys import stdin, stdout
input = stdin.readline
(n, s) = map(int, input().split())
ps = [0] * (10 ** 5 + 1)
pb = [0] * (10 ** 5 + 1)
for _ in range(n):
	(d, p, q) = input().split()
	p = int(p)
	q = int(q)
	if d == 'B':
		pb[p] += q
	else:
		ps[p] += q
cnt = 0
res1 = []
res2 = []
for i in range(10 ** 5 + 1):
	if ps[i] != 0:
		res1.append([i, ps[i]])
		cnt += 1
	if cnt == s:
		break
cnt = 0
for i in range(10 ** 5, -1, -1):
	if pb[i] != 0:
		res2.append([i, pb[i]])
		cnt += 1
	if cnt == s:
		break
res1.sort(reverse=True)
res2.sort(reverse=True)
for i in res1:
	stdout.write('S ' + str(i[0]) + ' ' + str(i[1]) + '\n')
for i in res2:
	stdout.write('B ' + str(i[0]) + ' ' + str(i[1]) + '\n')


from copy import *
from math import *
from collections import deque
import heapq
(n, s) = list(map(int, input().split()))
S = {}
B = {}
for i in range(n):
	(d, p, q) = list(map(str, input().split()))
	p = int(p)
	q = int(q)
	if d == 'S':
		if p not in S:
			S[p] = q
		else:
			S[p] += q
	elif p not in B:
		B[p] = q
	else:
		B[p] += q
SS = []
BB = []
for i in S:
	SS.append([i, S[i]])
for i in B:
	BB.append([i, B[i]])
SS = sorted(SS, reverse=True)
BB = sorted(BB, reverse=True)
GG = []
for i in range(min(s, len(SS))):
	GG.append(['S', SS[len(SS) - i - 1][0], SS[len(SS) - i - 1][1]])
GG = deepcopy(GG[-1::-1])
for i in range(len(GG)):
	print(GG[i][0], GG[i][1], GG[i][2])
for i in range(min(s, len(BB))):
	print('B', BB[i][0], BB[i][1])


s = input()
(n, d) = (int(s.split()[0]), int(s.split()[1]))
(b, s) = ({}, {})
(wb, ws) = ([], [])
for i in range(0, n):
	st = input().split()
	st[1] = int(st[1])
	st[2] = int(st[2])
	if st[0] == 'B':
		if st[1] not in b:
			b[st[1]] = st[2]
		else:
			b[st[1]] += st[2]
		if st[1] not in wb:
			wb.append(st[1])
	else:
		if st[1] not in s:
			s[st[1]] = st[2]
		else:
			s[st[1]] += st[2]
		if st[1] not in ws:
			ws.append(st[1])
ws.sort()
wb.sort(reverse=True)
ws = ws[:d]
wb = wb[:d]
ws.sort(reverse=True)
for i in ws:
	print('S %s %s' % (i, s[i]))
for i in wb:
	print('B %s %s' % (i, b[i]))


b = {}
s = {}
(n, k) = map(int, input().split())
for i in range(n):
	(d, p, q) = map(str, input().split())
	p = int(p)
	q = int(q)
	if d == 'B':
		b.setdefault(p)
		if b[p] == None:
			b[p] = q
		else:
			b[p] += q
	else:
		s.setdefault(p)
		if s[p] == None:
			s[p] = q
		else:
			s[p] += q
s1 = s.keys()
s1 = list(s1)
s1.sort()
b1 = b.keys()
b1 = list(b1)
b1.sort(reverse=True)
s1 = s1[:k]
s1.sort(reverse=True)
for i in range(min(k, len(s1))):
	print('S', s1[i], s[s1[i]])
for i in range(min(k, len(b1))):
	print('B', b1[i], b[b1[i]])


(n, m) = map(int, input().split())
d = {}
d1 = {}
for i in range(n):
	(a, b, c) = input().split()
	if a == 'B':
		d[a + ' ' + b] = d.get(a + ' ' + b, 0) + int(c)
	else:
		d1[a + ' ' + b] = d1.get(a + ' ' + b, 0) + int(c)
l = sorted(d, key=lambda x: int(x.split()[1]))
l1 = sorted(d1, key=lambda x: int(x.split()[1]))
ans = []
for i in range(min(m, len(l1))):
	ans.append(l1[i] + ' ' + str(d1[l1[i]]))
ans = ans[::-1]
for i in range(len(l) - 1, max(-1, len(l) - 1 - m), -1):
	ans.append(l[i] + ' ' + str(d[l[i]]))
for x in ans:
	print(x)


(n, m) = map(int, input().split())
B = {}
S = {}
for i in range(n):
	(a, b, c) = input().split()
	if a == 'B':
		w = -1 + int(b) + int(c)
		if (a, int(b)) not in B:
			B[a, int(b)] = int(c)
		else:
			B[a, int(b)] += int(c)
	elif (a, int(b)) not in S:
		S[a, int(b)] = int(c)
	else:
		S[a, int(b)] += int(c)
l = []
for i in B:
	(a, b) = i
	l.append((a, b, B[i]))
r = []
for i in S:
	(a, b) = i
	r.append((a, b, S[i]))
l.sort(key=lambda x: x[1], reverse=True)
r.sort(key=lambda x: x[1])
for i in range(min(m, len(r)) - 1, -1, -1):
	print(*r[i])
for i in range(min(m, len(l))):
	print(*l[i])


(q, n) = map(int, input().split())
sell = {}
buy = {}
for _ in range(q):
	s = input()
	if s[0] == 'B':
		(d, p, a) = s.split(' ')
		p = int(p)
		a = int(a)
		if p not in buy:
			buy[p] = a
		else:
			buy[p] += a
	else:
		(d, p, a) = s.split(' ')
		p = int(p)
		a = int(a)
		if p not in sell:
			sell[p] = a
		else:
			sell[p] += a
bb = sorted(buy.keys(), reverse=True)[:n]
ss = reversed(sorted(sell.keys())[:n])
for p in ss:
	print('S', p, sell[p])
for q in bb:
	print('B', q, buy[q])


R = lambda : map(int, input().split())
(n, s) = R()
(bs, ss) = ([0] * 100007, [0] * 100007)
for _ in range(n):
	(t, p, q) = input().split()
	(p, q) = (int(p), int(q))
	arr = bs if t == 'B' else ss
	arr[p] += q
(bres, sres) = ([], [])
for i in range(1, 10 ** 5 + 1):
	if ss[i] and len(sres) < s:
		sres.append('S ' + str(i) + ' ' + str(ss[i]))
for i in range(10 ** 5, -1, -1):
	if bs[i] and len(bres) < s:
		bres.append('B ' + str(i) + ' ' + str(bs[i]))
for x in sres[::-1]:
	print(x)
for x in bres:
	print(x)


from collections import defaultdict

def main():
	(n, s) = map(int, input().split())
	(sell, buy) = (defaultdict(lambda : 0), defaultdict(lambda : 0))
	for _ in range(n):
		(d, p, q) = input().split()
		if d[0] == 'S':
			sell[int(p)] += int(q)
		else:
			buy[int(p)] += int(q)
	for key in sorted(sell.keys())[s - 1::-1]:
		print('S {0} {1}'.format(key, sell[key]))
	for key in sorted(buy.keys())[::-1][:s]:
		print('B {0} {1}'.format(key, buy[key]))
main()


from sys import stdin
from collections import Counter

def main():
	(n, m) = map(int, input().split())
	d = {'B': Counter(), 'S': Counter()}
	for s in stdin.read().splitlines():
		(a, b, c) = s.split()
		d[a][int(b)] += int(c)
	for k in sorted(d['S'].keys(), reverse=True)[-m:]:
		print(f"S {k} {d['S'][k]}")
	for k in sorted(d['B'].keys(), reverse=True)[:m]:
		print(f"B {k} {d['B'][k]}")
main()


(num_orders, book_depth) = map(int, input().split())
buy_orders = {}
sell_orders = {}
for i in range(num_orders):
	tokens = input().split()
	direction = tokens[0]
	(price, volume) = map(int, tokens[1:])
	orders = buy_orders
	if direction == 'S':
		orders = sell_orders
	orders[price] = orders.setdefault(price, 0) + volume

def display(direction, order_list):
	if direction == 'B':
		order_list = order_list[:book_depth]
	else:
		order_list = order_list[-book_depth:]
	for order in order_list:
		print('%s %d %d' % (direction, order[0], order[1]))
sell_order_list = sorted(list(sell_orders.items()), key=lambda item: -item[0])
buy_order_list = sorted(list(buy_orders.items()), key=lambda item: -item[0])
display('S', sell_order_list)
display('B', buy_order_list)


from sys import stdin, stdout
input = stdin.readline
b = {}
s = {}
(n, l) = map(int, input().split(' '))
for i in range(n):
	(d, p, q) = input().split(' ')
	(p, q) = (int(p), int(q))
	if d == 'B':
		try:
			b[p] += q
		except KeyError:
			b[p] = q
	else:
		try:
			s[p] += q
		except KeyError:
			s[p] = q
for key in sorted(sorted(s)[0:min(l, len(s))], reverse=True):
	print('S %s %s' % (key, s[key]))
for key in sorted(b, reverse=True)[0:min(l, len(b))]:
	print('B %s %s' % (key, b[key]))


(n, s) = [int(i) for i in input().split()]
buys = {}
sells = {}
for i in range(n):
	order = input().split()
	d = order[0]
	p = int(order[1])
	q = int(order[2])
	if d == 'B':
		if p in buys:
			buys[p] += q
		else:
			buys[p] = q
	elif d == 'S':
		if p in sells:
			sells[p] += q
		else:
			sells[p] = q
buys_list = sorted([(k, v) for (k, v) in buys.items()], reverse=True)
sells_list = sorted([(k, v) for (k, v) in sells.items()])
l_sells_list = len(sells_list)
l_buys_list = len(buys_list)
if l_sells_list > s:
	if l_sells_list > 0:
		for i in range(s - 1, -1, -1):
			print('S ' + str(sells_list[i][0]) + ' ' + str(sells_list[i][1]))
elif l_sells_list > 0:
	for i in range(l_sells_list - 1, -1, -1):
		print('S ' + str(sells_list[i][0]) + ' ' + str(sells_list[i][1]))
if l_buys_list > s:
	if l_buys_list > 0:
		for i in range(s):
			print('B ' + str(buys_list[i][0]) + ' ' + str(buys_list[i][1]))
elif l_buys_list > 0:
	if l_buys_list > 0:
		for i in range(l_buys_list):
			print('B ' + str(buys_list[i][0]) + ' ' + str(buys_list[i][1]))


def arrint(array):
	for i in range(0, len(array)):
		array[i][1] = int(array[i][1])
		array[i][2] = int(array[i][2])
	return None

def found(price, array):
	for i in range(0, len(array)):
		if array[i][1] == price:
			return (True, i)
	return (False, 666)
(n, s) = map(int, input().split())
bidS = []
bidB = []
curbid = []
for i in range(n):
	curbid = list(map(str, input().split()))
	if curbid[0] == 'B':
		(ans, no) = found(curbid[1], bidB)
		if ans == False:
			bidB.append(curbid)
		else:
			bidB[no][2] = int(bidB[no][2]) + int(curbid[2])
	else:
		(ans, no) = found(curbid[1], bidS)
		if ans == False:
			bidS.append(curbid)
		else:
			bidS[no][2] = int(bidS[no][2]) + int(curbid[2])
arrint(bidS)
arrint(bidB)
bidB.sort()
bidS.sort()
if s > len(bidS):
	for i in range(len(bidS) - 1, -1, -1):
		print(' '.join(list(map(str, bidS[i]))))
else:
	for i in range(s - 1, -1, -1):
		print(' '.join(list(map(str, bidS[i]))))
if s > len(bidB):
	for i in range(len(bidB) - 1, -1, -1):
		print(' '.join(list(map(str, bidB[i]))))
else:
	for i in range(len(bidB) - 1, len(bidB) - s - 1, -1):
		print(' '.join(list(map(str, bidB[i]))))


(n, s) = map(int, input().split())
sem = [-1] * 100001
bum = [-1] * 100001
for i in range(n):
	(wh, p, q) = input().split()
	p = int(p)
	q = int(q)
	if wh == 'B':
		if bum[p] == -1:
			bum[p] = 0
		bum[p] += q
	else:
		if sem[p] == -1:
			sem[p] = 0
		sem[p] += q
fins = []
finb = []
ts = s
for i in range(100000, -1, -1):
	if not ts:
		break
	if bum[i] != -1:
		finb.append((i, bum[i]))
		ts -= 1
ts = s
for i in range(100001):
	if not ts:
		break
	if sem[i] != -1:
		fins.append((i, sem[i]))
		ts -= 1
ts = s
for i in range(len(fins) - 1, -1, -1):
	if not ts:
		break
	(a, b) = fins[i]
	print('S', a, b)
	ts -= 1
ts = s
for i in range(len(finb)):
	if not ts:
		break
	(a, b) = finb[i]
	print('B', a, b)
	ts -= 1


from collections import defaultdict as DD
from sys import stdin
input = stdin.readline
(n, s) = (int(x) for x in input().split())
B = DD(int)
S = DD(int)
for i in range(n):
	(d, p, q) = input().split()
	p = int(p)
	q = int(q)
	if d == 'B':
		B[p] += q
	else:
		S[p] += q
B = [('B', k, v) for (k, v) in B.items()]
S = [('S', k, v) for (k, v) in S.items()]
B.sort(key=lambda x: -x[1])
S.sort(key=lambda x: x[1])
B = B[:s]
S = S[:s]
S.sort(key=lambda x: -x[1])
print('\n'.join((x + ' ' + str(y) + ' ' + str(z) for (x, y, z) in S)))
print('\n'.join((x + ' ' + str(y) + ' ' + str(z) for (x, y, z) in B)))


(n, s) = list(map(int, input().split()))
(sell, buy) = ([], [])
for i in range(100003):
	sell.append(0)
	buy.append(0)
for i in range(n):
	(x, y, z) = input().split()
	if x == 'B':
		buy[int(y)] += int(z)
	else:
		sell[int(y)] += int(z)
(x, y) = (0, 0)
while x < s and y <= 100000:
	if sell[y] > 0:
		x += 1
	y += 1
while y >= 0:
	if sell[y] > 0:
		print('S', y, sell[y])
	y -= 1
(x, y) = (0, 100000)
while x < s and y >= 0:
	if buy[y] > 0:
		x += 1
		print('B', y, buy[y])
	y -= 1


import heapq
(n, s) = map(int, input().split())
applications_sell = []
applications_buy = []
for i in range(n):
	(cur1, cur2, cur3) = map(str, input().split())
	if cur1 == 'S':
		heapq.heappush(applications_sell, [cur1, int(cur2), int(cur3)])
	else:
		heapq.heappush(applications_buy, [cur1, -int(cur2), int(cur3)])
glass_sell = []
if len(applications_sell):
	glass_sell.append(heapq.heappop(applications_sell))
while len(applications_sell) > 0:
	cur = heapq.heappop(applications_sell)
	if glass_sell[-1][1] == cur[1]:
		glass_sell[-1][2] += cur[2]
	else:
		glass_sell.append(cur)
glass_buy = []
if len(applications_buy):
	glass_buy.append(heapq.heappop(applications_buy))
while len(applications_buy) > 0:
	cur = heapq.heappop(applications_buy)
	if glass_buy[-1][1] == cur[1]:
		glass_buy[-1][2] += cur[2]
	else:
		glass_buy.append(cur)
for i in range(min(len(glass_sell), s) - 1, -1, -1):
	print(glass_sell[i][0], glass_sell[i][1], glass_sell[i][2])
for i in range(min(len(glass_buy), s)):
	print(glass_buy[i][0], -glass_buy[i][1], glass_buy[i][2])


(n, s) = map(int, input().split())
(buy_dict, sell_dict) = ({}, {})
for _ in range(n):
	order = [val if i == 0 else int(val) for (i, val) in enumerate(input().split())]
	if order[0] == 'B':
		if order[1] in buy_dict:
			buy_dict[order[1]] += order[2]
		else:
			buy_dict[order[1]] = order[2]
	elif order[1] in sell_dict:
		sell_dict[order[1]] += order[2]
	else:
		sell_dict[order[1]] = order[2]
buy_list = sorted([(k, v) for (k, v) in buy_dict.items()], reverse=True)
sell_list = sorted([(k, v) for (k, v) in sell_dict.items()])
sell_list = sorted(sell_list[:s], reverse=True)
len_s = len(sell_list)
len_b = len(buy_list)
for i in range(s):
	if i < len_s:
		print('S {} {}'.format(sell_list[i][0], sell_list[i][1]))
	else:
		break
for i in range(s):
	if i < len_b:
		print('B {} {}'.format(buy_list[i][0], buy_list[i][1]))
	else:
		break


from sys import stdin, stdout, setrecursionlimit

class Tail_Recursion_Optimization:

	def __init__(self, RECURSION_LIMIT, STACK_SIZE):
		setrecursionlimit(RECURSION_LIMIT)
		threading.stack_size(STACK_SIZE)
		return None

class SOLVE:

	def solve(self):
		R = stdin.readline
		W = stdout.write
		(n, k) = [int(x) for x in R().split()]
		(b, s) = ({}, {})
		for i in range(n):
			(d, p, q) = [x for x in R().split()]
			p = int(p)
			q = int(q)
			if d == 'B':
				if p not in b:
					b[p] = q
				else:
					b[p] += q
			elif p not in s:
				s[p] = q
			else:
				s[p] += q
		b = list(b.items())
		s = list(s.items())
		b.sort(key=lambda x: x[0], reverse=True)
		s.sort(key=lambda x: x[0])
		for i in range(min(k, len(s)) - 1, -1, -1):
			W('S %d %d\n' % (s[i][0], s[i][1]))
		for i in range(min(k, len(b))):
			W('B %d %d\n' % (b[i][0], b[i][1]))
		return 0

def main():
	s = SOLVE()
	s.solve()
main()


__author__ = 'Andrey'
(n, s) = list(map(int, input().split()))
B = dict()
S = dict()
for i in range(n):
	t = input().split()
	if t[0] == 'B':
		B[int(t[1])] = B.get(int(t[1]), 0) + int(t[2])
	else:
		S[int(t[1])] = S.get(int(t[1]), 0) + int(t[2])
B_keys = sorted(list(B.keys()), reverse=True)
S_keys = sorted(S.keys())
if B_keys:
	b_s = B_keys[min(s - 1, len(B_keys) - 1)]
if S_keys:
	s_s = S_keys[min(s - 1, len(S_keys) - 1)]
	for key_1 in sorted(list(S.keys()), reverse=True):
		if key_1 <= s_s:
			print('S', key_1, S[key_1])
if B_keys:
	b_s = B_keys[min(s - 1, len(B_keys) - 1)]
	for key_2 in sorted(list(B.keys()), reverse=True):
		if key_2 >= b_s:
			print('B', key_2, B[key_2])


import time
(n, s) = (int(i) for i in input().split())
B = {}
S = {}
for i in range(n):
	(d, p, q) = (i for i in input().split())
	p = int(p)
	q = int(q)
	if d == 'B':
		if p not in B.keys():
			B[p] = q
		else:
			B[p] += q
	elif p not in S.keys():
		S[p] = q
	else:
		S[p] += q
start = time.time()
if s >= len(S):
	buf = S.keys()
else:
	buf = sorted(S.keys())
	buf = buf[:s]
for i in sorted(buf, key=lambda x: -x):
	print('S', i, S[i])
if s >= len(B):
	buf = B.keys()
else:
	buf = sorted(B.keys())
	buf = buf[-s:]
for i in sorted(buf, key=lambda x: -x):
	print('B', i, B[i])
finish = time.time()


(n, m) = map(int, input().split())
b = {}
s = {}
for _ in range(n):
	(u, v, w) = input().split()
	t = None
	if u == 'B':
		t = b
	else:
		t = s
	t[int(v)] = t.get(int(v), 0) + int(w)
s_k = list(sorted(s.keys()))
for i in range(min(m, len(s_k)) - 1, -1, -1):
	print('S ' + str(s_k[i]) + ' ' + str(s[s_k[i]]))
b_k = list(reversed(sorted(b.keys())))
for i in range(min(m, len(b_k))):
	print('B ' + str(b_k[i]) + ' ' + str(b[b_k[i]]))


(n, s) = map(int, input().split())
a = [[1000000000, -1] for i in range(100001)]
b = [[-1, -1] for i in range(100001)]
for i in range(n):
	s1 = list(map(str, input().split()))
	p = int(s1[1])
	depth = int(s1[2])
	if s1[0] == 'B':
		if b[p][0] == -1:
			b[p][0] = 0
			b[p][1] = p
		b[p][0] += depth
	else:
		if a[p][0] == 1000000000:
			a[p][0] = 0
			a[p][1] = p
		a[p][0] += depth
g = s
a1 = []
b1 = []
for i in range(len(a)):
	a1.append([i, a[i][0]])
for i in range(len(b)):
	b1.append([i, b[i][0]])
a1.sort()
b1.sort()
b1 = b1[::-1]
g = s
a3 = []
for i in range(len(a1)):
	if a1[i][1] != 1000000000:
		a3.append([a1[i][0], a1[i][1]])
		g = g - 1
	if g <= 0:
		break
a3.sort()
a3 = a3[::-1]
for i in range(len(a3)):
	print('S', a3[i][0], a3[i][1])
g = s
for i in range(len(b1)):
	if b1[i][1] != -1:
		print('B', b1[i][0], b1[i][1])
		g = g - 1
	if g <= 0:
		break


(n, s) = tuple(map(int, input().split()))
agr = dict()
for i in range(n):
	arr = input().split()
	arr[1] = int(arr[1])
	arr[2] = int(arr[2])
	agr[arr[0], arr[1]] = agr.get((arr[0], arr[1]), 0) + arr[2]
(sell, buy) = ([], [])
for elem in agr:
	if elem[0] == 'B':
		buy.append([elem[1], agr[elem]])
	else:
		sell.append([elem[1], agr[elem]])
sell.sort(key=lambda x: x[0])
buy.sort(key=lambda x: x[0], reverse=True)
buy = buy[:s]
sell = sell[:s]
sell.sort(key=lambda x: x[0], reverse=True)
for elem in sell:
	print('S', elem[0], elem[1])
for elem in buy:
	print('B', elem[0], elem[1])


(n, ss) = map(int, input().split())
(buy, send) = (dict(), dict())
for i in range(n):
	s = list(map(str, input().split()))
	c_v = list(map(int, s[1:]))
	if s[0] == 'B':
		if c_v[0] in buy:
			buy[c_v[0]] += c_v[1]
		else:
			buy[c_v[0]] = c_v[1]
	elif c_v[0] in send:
		send[c_v[0]] += c_v[1]
	else:
		send[c_v[0]] = c_v[1]
(length_s, length_b) = (len(send), len(buy))
buy_ = sorted(buy)[0 if length_b < ss else length_b - ss:]
send_ = sorted(send)[:min(length_s, ss)]
for i in range(len(send_) - 1, -1, -1):
	print('S', send_[i], send[send_[i]])
for i in range(len(buy_) - 1, -1, -1):
	print('B', buy_[i], buy[buy_[i]])


from collections import *
from itertools import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from sys import *

def fast():
	return stdin.readline().strip()

def zzz():
	return [int(i) for i in fast().split()]
(z, zz) = (input, lambda : list(map(int, z().split())))
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def output(answer):
	stdout.write(str(answer))
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
orders = {'B': {}, 'S': {}}
(n, s) = zzz()
for x in range(n):
	(d, p, q) = map(str, input().split())
	(p, q) = (int(p), int(q))
	try:
		orders[d][p] += q
	except:
		orders[d][p] = q
for p in list(reversed(list(sorted(orders['S']))[:s])):
	print('S', p, orders['S'][p])
for p in list(reversed(sorted(orders['B'])))[:s]:
	print('B', p, orders['B'][p])


from collections import defaultdict
from sys import stdin
inp = stdin.readline
(n, s) = map(int, inp().split())
buy = defaultdict(int)
sell = defaultdict(int)
ans = []
while n:
	n -= 1
	(o, p, q) = inp().split()
	if o == 'B':
		buy[int(p)] += int(q)
	else:
		sell[int(p)] += int(q)
buy_sorted = sorted(buy, reverse=True)[:s]
sell_sorted = sorted(sell)[:s]
sell_sorted.reverse()
for i in range(min(s, len(sell_sorted))):
	print('S', str(sell_sorted[i]), str(sell[sell_sorted[i]]))
for i in range(min(s, len(buy_sorted))):
	print('B', str(buy_sorted[i]), str(buy[buy_sorted[i]]))


import itertools as it
import functools
import operator
import collections
import math
import sys

def solve(xss, s):
	order = collections.defaultdict(int)
	for (d, p, q) in xss:
		order[d, int(p)] += int(q)
	sells = sorted([(d, p, q) for ((d, p), q) in order.items() if d == 'S'], reverse=True)
	buys = sorted([(d, p, q) for ((d, p), q) in order.items() if d == 'B'], reverse=True)
	return sells[-s:] + buys[:s]

def print_stderr(*args, **kwargs):
	print(*args, file=sys.stderr, **kwargs)

def main():
	[n, s] = [int(i) for i in input().strip().split()]
	xss = [input().strip().split() for _ in range(n)]
	result = solve(xss, s)
	for line in result:
		print(' '.join((str(n) for n in line)))
main()


import collections
(n, s) = map(int, input().split())
buy_orders = collections.defaultdict(int)
sell_orders = collections.defaultdict(int)
for i in range(n):
	(d, p, q) = input().split()
	(p, q) = (int(p), int(q))
	if d == 'B':
		buy_orders[p] += q
	else:
		sell_orders[p] += q
buy_orders = sorted(buy_orders.items(), reverse=True)
sell_orders = sorted(sell_orders.items(), reverse=True)
for order in sell_orders[-s:]:
	print('S', order[0], order[1])
for order in buy_orders[:s]:
	print('B', order[0], order[1])


B = [0] * (10 ** 5 + 2)
S = [0] * (10 ** 5 + 2)
(a, b) = list(map(int, input().split()))
for i in range(a):
	l = list(map(str, input().split()))
	if l[0] == 'S':
		S[int(l[1])] += int(l[2])
	if l[0] == 'B':
		B[int(l[1])] += int(l[2])
count = 0
ans = []
for i in range(10 ** 5 + 2):
	if S[i] != 0:
		count += 1
		ans.append(('S', i, S[i]))
		if count == b:
			break
for i in range(len(ans) - 1, -1, -1):
	print(ans[i][0], ans[i][1], ans[i][2])
count = 0
for i in range(10 ** 5 + 1, -1, -1):
	if B[i] != 0:
		count += 1
		print('B', i, B[i])
		if count == b:
			break


(n, m) = [int(x) for x in input().split()]
(a, b) = ({}, {})
for i in range(n):
	s = input().split()
	if s[0] == 'S':
		if int(s[1]) in a:
			a[int(s[1])] += int(s[2])
		else:
			a[int(s[1])] = int(s[2])
	elif int(s[1]) in b:
		b[int(s[1])] += int(s[2])
	else:
		b[int(s[1])] = int(s[2])
k = 0
r = []
for x in sorted(a):
	if k == m:
		break
	r.append([x, a[x]])
	k += 1
for i in r[::-1]:
	print('S', *i)
k = 0
for x in sorted(b, reverse=True):
	if k == m:
		break
	print('B', x, b[x])
	k += 1


from collections import defaultdict

class OrderBook:

	@staticmethod
	def _dict():
		return defaultdict(int)

	def __init__(self):
		(self._buy, self._sell) = (OrderBook._dict(), OrderBook._dict())

	@staticmethod
	def _add(book, price, volume):
		book[price] += volume

	def add_buy(self, price, volume):
		OrderBook._add(self._buy, price, volume)

	def add_sell(self, price, volume):
		OrderBook._add(self._sell, price, volume)

	@staticmethod
	def _entry(label, price, volume):
		return '%s %d %d' % (label, price, volume)

	def _get(self, book, label, start, end):
		keys = sorted(book.keys(), reverse=True)[start:end]
		return [OrderBook._entry(label, p, book[p]) for p in keys]

	def get_buy(self, s):
		return self._get(self._buy, 'B', 0, s)

	def get_sell(self, s):
		return self._get(self._sell, 'S', -s, len(self._sell))

def record(line):
	(d, p, q) = line
	return (d, int(p), int(q))
(n, s) = map(int, input().split())
book = OrderBook()
for _ in range(n):
	(d, p, q) = record(input().split())
	if d == 'B':
		book.add_buy(p, q)
	else:
		book.add_sell(p, q)
print('\n'.join(book.get_sell(s) + book.get_buy(s)))


(a, b) = map(int, input().split())
(bs, s) = ({}, {})
for _ in ' ' * a:
	(x, y, z) = input().split()
	(y, z) = (int(y), int(z))
	if x == 'B':
		if y in bs:
			bs[y] += z
		else:
			bs[y] = z
	elif y in s:
		s[y] += z
	else:
		s[y] = z
z = [['S', i, s[i]] for i in sorted(s)][:b][::-1]
z1 = [['B', i, bs[i]] for i in sorted(bs, reverse=True)][:b]
for i in z:
	print(*i)
for i in z1:
	print(*i)


(n, s) = map(int, input().split())
sell = {}
buy = {}
lb = []
ls = []
ks = 0
kb = 0
for _ in range(n):
	(d, p, q) = map(str, input().split())
	if d == 'B':
		if d + p in buy:
			buy[d + p] += int(q)
		else:
			lb.append(int(p))
			buy[d + p] = int(q)
	elif d + p in sell:
		sell[d + p] += int(q)
	else:
		ls.append(int(p))
		ks += 1
		sell[d + p] = int(q)
ls.sort()
lb.sort(reverse=1)
k = 0
for i in range(min(ks, s) - 1, -1, -1):
	print('S', ls[i], sell['S' + str(ls[i])])
k = 0
for x in lb:
	if k < s:
		print('B', x, buy['B' + str(x)])
	else:
		break
	k += 1


(n, k) = map(int, input().split())
bb = {}
ss = {}
for i in range(n):
	(a, b, c) = input().split()
	b = int(b)
	c = int(c)
	if a == 'B':
		if b in bb:
			bb[b] += int(c)
		else:
			bb[b] = int(c)
	elif b in ss:
		ss[b] += int(c)
	else:
		ss[b] = int(c)
buy = sorted(bb.items(), reverse=True)[:k]
sell = reversed(sorted(ss.items())[:k])
for (pi, qi) in sell:
	print('S', pi, qi)
for (pi, qi) in buy:
	print('B', pi, qi)


(n, ss) = map(int, input().split())
b = list()
s = list()
for i in range(n):
	a = input().split()
	if a[0] == 'B':
		b.append(list(map(int, a[1:])))
	else:
		s.append(list(map(int, a[1:])))
b.sort(key=lambda x: x[0], reverse=True)
s.sort(key=lambda x: x[0], reverse=True)
k = 0
for i in range(len(b) - 1):
	try:
		if b[i - k][0] == b[i - k + 1][0]:
			b[i - k + 1][1] += b[i - k][1]
			b.pop(i - k)
			k += 1
	except IndexError:
		break
k = 0
for i in range(len(s) - 1):
	try:
		if s[i - k][0] == s[i - k + 1][0]:
			s[i - k + 1][1] += s[i - k][1]
			s.pop(i - k)
			k += 1
	except IndexError:
		break
if ss < len(s):
	s = s[len(s) - ss:]
for i in range(len(s)):
	print('S', *s[i])
for i in range(min(len(b), ss)):
	print('B', *b[i])


from sys import stdin, stdout
input = stdin.readline
(n, s) = map(int, input().split())
buy = {}
sell = {}
for _ in range(n):
	(mov, p, q) = input().split()
	p = int(p)
	q = int(q)
	if mov == 'B':
		buy[p] = buy.get(p, 0) + q
	else:
		sell[p] = sell.get(p, 0) + q
bkeys = sorted(buy.keys(), reverse=True)[:s]
skeys = sorted(sell.keys())[:s]
for key in reversed(skeys):
	stdout.write('S {} {}\n'.format(key, sell[key]))
for key in bkeys:
	stdout.write('B {} {}\n'.format(key, buy[key]))


from collections import defaultdict
(n, s) = input().split()
(n, s) = (int(n), int(s))
b_orders = defaultdict(int)
s_orders = defaultdict(int)
for _ in range(n):
	(d, p, q) = input().split()
	(p, q) = (int(p), int(q))
	if d == 'B':
		b_orders[p] += q
	else:
		s_orders[p] += q
b_orders = list(sorted(b_orders.items(), reverse=True))
s_orders = list(sorted(s_orders.items(), reverse=True))
beg = max(0, len(s_orders) - s)
for order in s_orders[beg:]:
	print('S', order[0], order[1])
end = min(len(b_orders), s)
for order in b_orders[:end]:
	print('B', order[0], order[1])


from collections import defaultdict
(n, s) = map(int, input().split(' '))
B = defaultdict(lambda : 0)
S = defaultdict(lambda : 0)
for _ in range(n):
	(d, p, q) = input().split(' ')
	if d == 'B':
		B[int(p)] += int(q)
	else:
		S[int(p)] += int(q)
b_keys = sorted(B.keys(), reverse=True)[:s]
s_keys = sorted(S.keys())[:s]
if len(s_keys) > 0:
	for i in range(min(s, len(s_keys)) - 1, -1, -1):
		print(f'S {s_keys[i]} {S[s_keys[i]]}')
if len(b_keys) > 0:
	for i in range(min(s, len(b_keys))):
		print(f'B {b_keys[i]} {B[b_keys[i]]}')


(n, s) = map(int, input().split())
l = []
ll = []
for i in range(n):
	pp = input().split()
	pp = [pp[0], int(pp[1]), int(pp[2])]
	if pp[0] == 'B':
		ll.append(pp)
	else:
		l.append(pp)
ll.sort(key=lambda x: x[1], reverse=True)
l.sort(key=lambda x: x[1])
for i in range(len(l) - 1):
	t = l[i]
	tt = l[i + 1]
	if t[1] == tt[1]:
		l[i + 1] = [t[0], t[1], t[2] + tt[2]]
		l[i] = False
for i in range(len(ll) - 1):
	t = ll[i]
	tt = ll[i + 1]
	if t[1] == tt[1]:
		ll[i + 1] = [t[0], t[1], t[2] + tt[2]]
		ll[i] = False
p = 0
px = 0
r = []
while p < s and px < len(l):
	if l[px] != False:
		r.append(l[px])
		px += 1
		p += 1
	else:
		px += 1
for i in range(-1, -len(r) - 1, -1):
	print(*r[i])
p = 0
px = 0
while p < s and px < len(ll):
	if ll[px] != False:
		print(*ll[px])
		px += 1
		p += 1
	else:
		px += 1


import collections, itertools, functools, math

def solve():
	(n, s) = map(int, input().split())
	buy = collections.Counter()
	sell = collections.Counter()
	for _ in range(n):
		(d, p, q) = input().split()
		p = int(p)
		q = int(q)
		if d == 'B':
			buy[p] += q
		else:
			sell[p] += q
	buy = buy.most_common()
	buy.sort(reverse=True)
	buy = buy[:s]
	sell = sell.most_common()
	sell.sort()
	sell = sell[:s]
	sell.reverse()
	for (p, q) in sell:
		print('S', p, q)
	for (p, q) in buy:
		print('B', p, q)
solve()


import sys
import os

def getint():
	return list(map(int, input().split(' ')))
(n, s) = getint()
dic = {'B': {}, 'S': {}}
for i in range(n):
	(d, p, q) = list(input().split(' '))
	p = int(p)
	q = int(q)
	dic[d][p] = dic[d].get(p, 0) + q
for key in sorted(dic['S'], reverse=True)[-s:]:
	print('S', key, dic['S'][key])
for key in sorted(dic['B'], reverse=True)[:s]:
	print('B', key, dic['B'][key])


(n, s) = list(map(int, input().split()))
B = []
S = []
for i in range(n):
	st = list(input().split())
	(st[1], st[2]) = (int(st[1]), int(st[2]))
	if st[0] == 'B':
		B.append(st)
	else:
		S.append(st)
B.sort()
S.sort()
i = 0
while i < len(B) - 1:
	if B[i][1] == B[i + 1][1]:
		B[i][2] += B[i + 1][2]
		del B[i + 1]
	else:
		i += 1
i = 0
while i < len(S) - 1:
	if S[i][1] == S[i + 1][1]:
		S[i][2] += S[i + 1][2]
		del S[i + 1]
	else:
		i += 1
B.reverse()
b = []
for i in range(min(s, len(S))):
	b.append(S[i])
b.reverse()
for i in range(len(b)):
	print(*b[i])
for i in range(min(s, len(B))):
	print(*B[i])


(n, m) = map(int, input().split())
s = {}
b = {}
for _ in range(n):
	a = list(input().split())
	if a[0] == 'S':
		if int(a[1]) in s:
			s[int(a[1])] += int(a[2])
		else:
			s[int(a[1])] = int(a[2])
	elif int(a[1]) in b:
		b[int(a[1])] += int(a[2])
	else:
		b[int(a[1])] = int(a[2])
[print('S', i, s[i]) for i in list(sorted(s)[min(m - 1, len(s))::-1])]
[print('B', i, b[i]) for i in list(sorted(b)[len(b) - min(m, len(b)):])[::-1]]
1


(n, s) = map(int, input().split())
sell = {}
buy = {}
for i in range(n):
	(type, price, vol) = input().split()
	price = int(price)
	vol = int(vol)
	if type == 'S':
		sell[price] = sell.get(price, 0) + vol
	else:
		buy[price] = buy.get(price, 0) + vol
for order in sorted(sell.items(), reverse=True)[-s:]:
	print('S', order[0], order[1])
for order in sorted(buy.items(), reverse=True)[:s]:
	print('B', order[0], order[1])


(n, s) = map(int, input().split())
buy = {}
sell = {}
while n > 0:
	(ccc, p, q) = input().split()
	p = int(p)
	q = int(q)
	if ccc == 'B':
		if p in buy:
			buy[p] += q
		else:
			buy[p] = q
	elif p in sell:
		sell[p] += q
	else:
		sell[p] = q
	n -= 1
arr = sell.keys()
arr = sorted(arr)
for i in arr[s - 1::-1]:
	print('S', i, sell[i])
arr = buy.keys()
arr = sorted(arr)
arr.reverse()
for i in arr[0:s]:
	print('B', i, buy[i])


s = [0] * 100010
b = [0] * 100010
temps = []
tempb = []
(n, m) = map(int, input().split())
for _ in range(n):
	(d, p, q) = input().split(' ')
	if d == 'S':
		s[int(p)] += int(q)
	else:
		b[int(p)] += int(q)
for i in range(100010):
	if s[i]:
		temps.append([i, s[i]])
	if b[i]:
		tempb.append([i, b[i]])
temps = temps[:m]
tempb = tempb[::-1]
tempb = tempb[:m]
for i in temps[::-1]:
	print('S', i[0], i[1])
for i in tempb:
	print('B', i[0], i[1])


import sys, os.path
from collections import *
from copy import *
import math
mod = 10 ** 9 + 7
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
(n, s) = map(int, input().split())
mat = []
buy = {}
sell = {}
for i in range(n):
	dpq = list(map(str, input().split()))
	d = dpq[0]
	p = int(dpq[1])
	q = int(dpq[2])
	if d == 'S':
		sell[p] = sell.get(p, 0) + q
	else:
		buy[p] = buy.get(p, 0) + q
b = list(buy.items())
b.sort()
sel = list(sell.items())
sel.sort()
b = b[-s:]
sel = sel[:s]
b.reverse()
sel.reverse()
for i in sel:
	print('S', *i)
for i in b:
	print('B', *i)


(n, s) = map(int, input().split())
(buys, sells) = ({}, {})
for i in range(n):
	line = input().split()
	d = line[0]
	p = int(line[1])
	v = int(line[2])
	if d == 'B':
		if p in buys:
			buys[p] += v
		else:
			buys[p] = v
	elif p in sells:
		sells[p] += v
	else:
		sells[p] = v
sells = sorted(sells.items())[:s]
buys = sorted(buys.items(), reverse=True)[:s]
for sell in sells[::-1]:
	print('S', sell[0], sell[1])
for buy in buys:
	print('B', buy[0], buy[1])


(buy, sell) = ({}, {})
(n, depth) = map(int, input().split())
for i in range(n):
	(direction, price, volume) = input().split()
	(price, volume) = (int(price), int(volume))
	if direction == 'B':
		if price in buy:
			buy[price] += volume
		else:
			buy[price] = volume
	elif price in sell:
		sell[price] += volume
	else:
		sell[price] = volume
for price in sorted(sell.keys())[depth - 1::-1]:
	print('S {price} {volume}'.format(price=price, volume=sell[price]))
for price in sorted(buy.keys())[:-depth - 1:-1]:
	print('B {price} {volume}'.format(price=price, volume=buy[price]))


from itertools import groupby
(n, s) = [int(x) for x in input().split()]
(B, S) = ([], [])
for i in range(n):
	order = input().split()
	X = B if order[0] == 'B' else S
	X.append((int(order[1]), int(order[2])))
B.sort()
S.sort()
B1 = ['B {0} {1}'.format(k, sum((v[1] for v in V))) for (k, V) in groupby(B, key=lambda p: p[0])]
S1 = ['S {0} {1}'.format(k, sum((v[1] for v in V))) for (k, V) in groupby(S, key=lambda p: p[0])]
book = reversed(B1[-s:] + S1[:s])
for order in book:
	print(order)


(n, s) = [int(x) for x in input().split(' ')]
buy = []
sell = []
for i in range(n):
	orden = input().split(' ')
	d = orden[0]
	precio = int(orden[1])
	volumen = int(orden[2])
	existe = False
	if d == 'B':
		for i in range(len(buy)):
			if buy[i][0] == precio:
				buy[i][1] += volumen
				existe = True
				break
		if existe == False:
			buy.append([precio, volumen])
	else:
		for i in range(len(sell)):
			if sell[i][0] == precio:
				sell[i][1] += volumen
				existe = True
				break
		if existe == False:
			sell.append([precio, volumen])
lineas = 1
impSell = []
while lineas <= s:
	if len(sell) > 0:
		impSell.insert(0, min(sell))
		sell.remove(min(sell))
	lineas += 1
cont = 1
for imp in impSell:
	if cont <= s:
		print('S ' + str(imp[0]) + ' ' + str(imp[1]))
		cont += 1
lineas = 1
while lineas <= s:
	if len(buy) > 0:
		print('B ' + str(max(buy)[0]) + ' ' + str(max(buy)[1]))
		buy.remove(max(buy))
	lineas += 1


import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy
from itertools import chain, dropwhile, permutations, combinations
from collections import defaultdict, deque

def VI():
	return list(map(int, input().split()))

def I():
	return int(input())

def LIST(n, m=None):
	return [0] * n if m is None else [[0] * m for i in range(n)]

def main(info=0):
	(n, s) = VI()
	(d, p, q) = (LIST(n), LIST(n), LIST(n))
	db = {}
	ds = {}
	for i in range(n):
		(d[i], p[i], q[i]) = input().split()
	p = [int(x) for x in p]
	q = [int(x) for x in q]
	for i in range(n):
		if d[i] == 'B':
			if p[i] in db:
				db[p[i]] = db[p[i]] + q[i]
			else:
				db[p[i]] = q[i]
		if d[i] == 'S':
			if p[i] in ds:
				ds[p[i]] = ds[p[i]] + q[i]
			else:
				ds[p[i]] = q[i]
	lb = sorted(list(db.items()))[::-1][:s]
	ls = sorted(list(ds.items()))[:s][::-1]
	for (k, v) in ls:
		print('S {} {}'.format(k, v))
	for (k, v) in lb:
		print('B {} {}'.format(k, v))

def __starting_point():
	main()
__starting_point()


(n, s) = [int(i) for i in input().split()]
arr_s = []
arr_b = []
for i in range(n):
	s1 = input().split()
	if s1[0] == 'S':
		arr_s.append([s1[0], int(s1[1]), int(s1[2])])
	else:
		arr_b.append([s1[0], int(s1[1]), int(s1[2])])
for i in range(len(arr_s)):
	for j in range(len(arr_s) - i - 1):
		if arr_s[j][1] < arr_s[j + 1][1]:
			(arr_s[j], arr_s[j + 1]) = (arr_s[j + 1], arr_s[j])
for i in range(len(arr_b)):
	for j in range(len(arr_b) - i - 1):
		if arr_b[j][1] > arr_b[j + 1][1]:
			(arr_b[j], arr_b[j + 1]) = (arr_b[j + 1], arr_b[j])
i = 0
while i < len(arr_s) - 1:
	if arr_s[i][1] == arr_s[i + 1][1]:
		arr_s[i][2] += arr_s[i + 1][2]
		arr_s.pop(i + 1)
	else:
		i += 1
i = 0
while i < len(arr_b) - 1:
	if arr_b[i][1] == arr_b[i + 1][1]:
		arr_b[i][2] += arr_b[i + 1][2]
		arr_b.pop(i + 1)
	else:
		i += 1
if len(arr_s) > s:
	for i in range(len(arr_s) - s, len(arr_s)):
		print(arr_s[i][0], arr_s[i][1], arr_s[i][2])
else:
	for i in arr_s:
		print(i[0], i[1], i[2])
o = 1
for i in range(len(arr_b) - 1, -1, -1):
	if o <= s:
		print(arr_b[i][0], arr_b[i][1], arr_b[i][2])
	o += 1


MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
(dbuy, dsell) = ({}, {})
(n, k) = f()
for _ in range(n):
	(bos, pr, q) = input().split()
	pr = int(pr)
	q = int(q)
	if bos == 'B':
		if pr in dbuy:
			dbuy[pr] += q
		else:
			dbuy[pr] = q
	elif pr in dsell:
		dsell[pr] += q
	else:
		dsell[pr] = q
for i in list(sorted(dsell.items()))[:k][::-1]:
	print('S', *i)
for i in list(sorted(dbuy.items(), reverse=True))[:k]:
	print('B', *i)


(n, s) = map(int, input().split())
dic1 = {}
dic2 = {}
array = []
for i in range(n):
	(a, b, c) = input().split()
	b = int(b)
	c = int(c)
	if a == 'B':
		dic1[b] = dic1.get(b, 0) + c
	else:
		dic2[b] = dic2.get(b, 0) + c
buy_list = sorted(dic1.items(), reverse=True)[:s]
sell_list = reversed(sorted(dic2.items())[:s])
for (k, v) in sell_list:
	print('S', k, v)
for (k, v) in buy_list:
	print('B', k, v)


from collections import defaultdict
(n, depth) = [int(x) for x in input().split(' ')]
l = []
s = defaultdict(int)
b = defaultdict(int)
sl = []
bl = []
for i in range(n):
	(d, p, q) = [x for x in input().split(' ')]
	p = int(p)
	q = int(q)
	if d == 'S':
		s[p] += q
	else:
		b[p] += q
for (p, q) in s.items():
	sl += [(p, q)]
for (p, q) in b.items():
	bl += [(p, q)]
sl.sort()
bl.sort()
sp = ['S {0} {1}'.format(i[0], i[1]) for i in sorted(sl[0:depth], key=lambda x: -x[0])]
bp = ['B {0} {1}'.format(i[0], i[1]) for i in bl[-1:-depth - 1:-1]]
for i in sp + bp:
	print(i)


(n, s) = map(int, input().split())
pricesell = dict()
pricebuy = dict()
sellp = set()
buyp = set()
for i in range(n):
	tmp = input().split()
	if tmp[0] == 'B':
		if int(tmp[1]) in buyp:
			pricebuy[int(tmp[1])] += int(tmp[2])
		else:
			pricebuy[int(tmp[1])] = int(tmp[2])
		buyp.add(int(tmp[1]))
	else:
		if int(tmp[1]) in sellp:
			pricesell[int(tmp[1])] += int(tmp[2])
		else:
			pricesell[int(tmp[1])] = int(tmp[2])
		sellp.add(int(tmp[1]))
buy = list(pricebuy.items())
sell = list(pricesell.items())
buy.sort(reverse=True)
sell.sort()
buy1 = buy[:min(s, len(buy))]
sell1 = sell[:min(s, len(sell))]
sell1.sort(reverse=True)
buy1 = list(map(lambda x: 'B ' + str(x[0]) + ' ' + str(x[1]), buy1))
sell1 = list(map(lambda x: 'S ' + str(x[0]) + ' ' + str(x[1]), sell1))
print(*sell1, sep='\n')
print(*buy1, sep='\n')


(n, x) = map(int, input().split())
a = [0] * 100001
for i in range(n):
	s = list(input().split())
	p = int(s[1])
	q = int(s[2])
	if s[0] == 'S':
		a[p] += q
	else:
		a[p] -= q
p = len(a) - 1
c = 0
for i in range(0, len(a)):
	if a[i] > 0:
		c += 1
	if c == x:
		p = i
		break
for i in range(p, -1, -1):
	if a[i] > 0:
		print('S', end=' ')
		print(i, a[i])
p = 0
for i in range(len(a) - 1, -1, -1):
	if a[i] < 0:
		print('B', end=' ')
		print(i, -1 * a[i])
		p += 1
	if p == x:
		break


read = lambda : map(int, input().split())
(n, s) = read()
S = {}
B = {}
for i in range(n):
	(d, p, q) = input().split()
	(p, q) = (int(p), int(q))
	if d == 'S':
		if S.get(p) is None:
			S[p] = q
		else:
			S[p] += q
	elif B.get(p) is None:
		B[p] = q
	else:
		B[p] += q
lens = min(s, len(S))
lenb = min(s, len(B))
S1 = list(reversed(sorted(S)[:lens]))
B1 = sorted(B, reverse=True)[:lenb]
for i in range(lens):
	print('S', S1[i], S[S1[i]])
for i in range(lenb):
	print('B', B1[i], B[B1[i]])


from sys import stdin, stdout
from collections import Counter

def ai():
	return list(map(int, stdin.readline().split()))

def ei():
	return map(int, stdin.readline().split())

def ip():
	return int(stdin.readline().strip())

def op(ans):
	return stdout.write(str(ans) + '\n')
(n, s) = ei()
li = []
for _ in range(n):
	(d, p, q) = input().split()
	li.append((d, int(p), int(q)))
rem = set()
new_li = []
idx = idx2 = -1
for (d1, p1, q1) in li:
	idx += 1
	idx2 = -1
	final_q = q1
	for (d2, p2, q2) in li:
		idx2 += 1
		if d1 == d2 and p1 == p2 and (idx2 != idx):
			final_q += q2
			rem.add(idx2)
			rem.add(idx)
	if final_q > q1:
		new_li.append((d1, p1, final_q))
new_li = list(set(new_li))
rem = list(rem)
for i in range(n):
	if i not in rem:
		new_li.append(li[i])
li = new_li
buy = [i for i in li if i[0] == 'B']
sell = [i for i in li if i[0] == 'S']
buy = sorted(buy, key=lambda x: x[1])[::-1][:s]
sell = sorted(sell, key=lambda x: x[1])[::-1][-s:]
try:
	for i in sell:
		print(*i)
except:
	pass
try:
	for i in buy:
		print(*i)
except:
	pass


(n, s) = map(int, input().split())
dic = {'B': {}, 'S': {}}
for i in range(n):
	(d, p, q) = list(input().split(' '))
	(p, q) = (int(p), int(q))
	dic[d][p] = dic[d].get(p, 0) + q
for k in sorted(dic['S'], reverse=True)[-s:]:
	print('S', k, dic['S'][k])
for k in sorted(dic['B'], reverse=True)[:s]:
	print('B', k, dic['B'][k])


import operator
from collections import OrderedDict
data = [int(info) for info in input().split(' ')]
length = data[0]
depth = data[1]
order_dict = {'B': OrderedDict(), 'S': OrderedDict()}
for i in range(0, length):
	data = input().split()
	if int(data[1]) in order_dict[data[0]].keys():
		order_dict[data[0]][int(data[1])] += int(data[2])
	else:
		order_dict[data[0]][int(data[1])] = int(data[2])
order_s = list(sorted(order_dict['S'].keys()))
order_b = list(reversed(sorted(order_dict['B'].keys())))
if len(order_s) > 0:
	if len(order_s) > depth:
		for i in list(reversed(range(0, depth))):
			print('S {} {}'.format(order_s[i], order_dict['S'][order_s[i]]))
	else:
		for i in list(reversed(range(0, len(order_s)))):
			print('S {} {}'.format(order_s[i], order_dict['S'][order_s[i]]))
if len(order_b) > 0:
	if len(order_b) > depth:
		for i in range(0, depth):
			print('B {} {}'.format(order_b[i], order_dict['B'][order_b[i]]))
	else:
		for i in range(0, len(order_b)):
			print('B {} {}'.format(order_b[i], order_dict['B'][order_b[i]]))


(n, z) = map(int, input().split())
b = []
s = []
for i in range(n):
	h = input().split()
	if h[0] == 'B':
		bb = True
		for j in range(len(b)):
			(x, y) = b[j]
			if x == int(h[1]):
				b[j] = (x, y + int(h[2]))
				bb = False
		if bb:
			b += [(int(h[1]), int(h[2]))]
	else:
		bb = True
		for j in range(len(s)):
			(x, y) = s[j]
			if x == int(h[1]):
				s[j] = (x, y + int(h[2]))
				bb = False
		if bb:
			s += [(int(h[1]), int(h[2]))]
b = sorted(b, key=lambda colonnes: colonnes[0])
s = sorted(s, key=lambda colonnes: colonnes[0])
i = 0
h = 0
while h < z and len(s) - 1 - i >= 0:
	if len(s) - 1 - i < z:
		print('S', s[len(s) - 1 - i][0], s[len(s) - 1 - i][1])
		h += 1
	i += 1
for i in range(z):
	if len(b) - 1 - i >= 0:
		print('B', b[len(b) - 1 - i][0], b[len(b) - 1 - i][1])


orders = {'B': {}, 'S': {}}
(n, s) = map(int, input().split())
for x in range(n):
	(d, p, q) = map(str, input().split())
	(p, q) = (int(p), int(q))
	try:
		orders[d][p] += q
	except:
		orders[d][p] = q
for p in list(reversed(list(sorted(orders['S']))[:s])):
	print('S', p, orders['S'][p])
for p in list(reversed(sorted(orders['B'])))[:s]:
	print('B', p, orders['B'][p])


(n, s) = map(int, input().split())
sell = []
buy = []
for i in range(100003):
	sell.append(0)
	buy.append(0)
for i in range(n):
	(a, b, c) = input().split()
	if a == 'B':
		buy[int(b)] += int(c)
	else:
		sell[int(b)] += int(c)
it = 0
nr = 0
while it < s and nr <= 100000:
	if sell[nr] > 0:
		it += 1
	nr += 1
while nr >= 0:
	if sell[nr] > 0:
		print('S', nr, sell[nr])
	nr -= 1
it = 0
nr = 100000
while it < s and nr >= 0:
	if buy[nr] > 0:
		it += 1
		print('B', nr, buy[nr])
	nr -= 1


R = lambda : map(str, input().rstrip().split())
(n, s) = map(int, input().rstrip().split())
bp = [-1] * 100001
sp = [-1] * 100001
buy = []
sell = []
for i in range(n):
	(d, p, q) = R()
	p = int(p)
	q = int(q)
	if d == 'B':
		if bp[p] >= 0:
			buy[bp[p]][2] += q
		else:
			buy.append([i, p, q])
			bp[p] = len(buy) - 1
	elif sp[p] >= 0:
		sell[sp[p]][2] += q
	else:
		sell.append([i, p, q])
		sp[p] = len(sell) - 1
ans_buy = []
buy.sort(reverse=True, key=lambda x: x[1])
for i in range(min(s, len(buy))):
	ans_buy.append(buy[i])
ans_sell = []
sell.sort(key=lambda x: x[1])
for i in range(min(s, len(sell))):
	ans_sell.append(sell[i])
ans_sell.sort(reverse=True, key=lambda x: x[1])
for x in ans_sell:
	print('S', x[1], x[2])
for x in ans_buy:
	print('B', x[1], x[2])


s = []
b = []
bd = [0] * 1000000
sd = [0] * 1000000
pas = []
pab = []
(n, k) = list(map(int, input().split()))
for i in range(n):
	(t, p, v) = list(input().split(' '))
	(p, v) = (int(p), int(v))
	if t == 'B':
		bd[p] += v
		pab.append(p)
	else:
		sd[p] += v
		pas.append(p)
pas = set(pas)
pab = set(pab)
for i in pas:
	s.append(('S', i, sd[i]))
for i in pab:
	b.append(('B', i, bd[i]))
s.sort(key=lambda x: x[1])
b.sort(key=lambda x: x[1], reverse=True)
for i in range(min(len(s) - 1, k - 1), -1, -1):
	print(*s[i])
for i in range(min(len(b), k)):
	print(*b[i])