You have got a shelf and want to put some books on it.

You are given $q$ queries of three types:  L $id$ — put a book having index $id$ on the shelf to the left from the leftmost existing book;  R $id$ — put a book having index $id$ on the shelf to the right from the rightmost existing book;  ? $id$ — calculate the minimum number of books you need to pop from the left or from the right in such a way that the book with index $id$ will be leftmost or rightmost. 

You can assume that the first book you will put can have any position (it does not matter) and queries of type $3$ are always valid (it is guaranteed that the book in each such query is already placed). You can also assume that you don't put the same book on the shelf twice, so $id$s don't repeat in queries of first two types.

Your problem is to answer all the queries of type $3$ in order they appear in the input.

Note that after answering the query of type $3$ all the books remain on the shelf and the relative order of books does not change.

If you are Python programmer, consider using PyPy instead of Python when you submit your code.


-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries.

Then $q$ lines follow. The $i$-th line contains the $i$-th query in format as in the problem statement. It is guaranteed that queries are always valid (for query type $3$, it is guaranteed that the book in each such query is already placed, and for other types, it is guaranteed that the book was not placed before).

It is guaranteed that there is at least one query of type $3$ in the input.

In each query the constraint $1 \le id \le 2 \cdot 10^5$ is met.


-----Output-----

Print answers to queries of the type $3$ in order they appear in the input.


-----Examples-----
Input
8
L 1
R 2
R 3
? 2
L 4
? 1
L 5
? 1

Output
1
1
2

Input
10
L 100
R 100000
R 123
L 101
? 123
L 10
R 115
? 100
R 110
? 115

Output
0
2
1



-----Note-----

Let's take a look at the first example and let's consider queries:   The shelf will look like $[1]$;  The shelf will look like $[1, 2]$;  The shelf will look like $[1, 2, 3]$;  The shelf looks like $[1, \textbf{2}, 3]$ so the answer is $1$;  The shelf will look like $[4, 1, 2, 3]$;  The shelf looks like $[4, \textbf{1}, 2, 3]$ so the answer is $1$;  The shelf will look like $[5, 4, 1, 2, 3]$;  The shelf looks like $[5, 4, \textbf{1}, 2, 3]$ so the answer is $2$. 

Let's take a look at the second example and let's consider queries:   The shelf will look like $[100]$;  The shelf will look like $[100, 100000]$;  The shelf will look like $[100, 100000, 123]$;  The shelf will look like $[101, 100, 100000, 123]$;  The shelf looks like $[101, 100, 100000, \textbf{123}]$ so the answer is $0$;  The shelf will look like $[10, 101, 100, 100000, 123]$;  The shelf will look like $[10, 101, 100, 100000, 123, 115]$;  The shelf looks like $[10, 101, \textbf{100}, 100000, 123, 115]$ so the answer is $2$;  The shelf will look like $[10, 101, 100, 100000, 123, 115, 110]$;  The shelf looks like $[10, 101, 100, 100000, 123, \textbf{115}, 110]$ so the answer is $1$.

Difficulty: MEDIUM
Tags: Implementation

Starter code:

Solutions:
leftmost = 1000000
rightmost = leftmost - 1
all_books = dict()
q = int(input())
for _ in range(q):
	(q_type, q_book) = input().split()
	if q_type == 'L':
		leftmost -= 1
		all_books[q_book] = leftmost
	elif q_type == 'R':
		rightmost += 1
		all_books[q_book] = rightmost
	else:
		print(min(rightmost - all_books[q_book], all_books[q_book] - leftmost))


q = int(input())
pos = {}
(left, right) = (0, 1)
for i in range(q):
	data = input().split()
	command = data[0]
	x = int(data[1])
	if command == 'L':
		pos[x] = left
		left -= 1
	if command == 'R':
		pos[x] = right
		right += 1
	if command == '?':
		real_pos = pos[x] - (left + 1)
		n = right - left - 1
		print(min(real_pos, n - 1 - real_pos))


N = int(input())
(l, r) = (1, 0)
dic = {}
for i in range(N):
	(a, b) = input().split()
	if a == 'L':
		dic[b] = l - 1
		l -= 1
	elif a == 'R':
		dic[b] = r + 1
		r += 1
	else:
		print(min(abs(dic[b] - l), abs(r - dic[b])))


n = int(input())
a = [0] * 200001
mi = 0
ma = 0
input()
for i in range(n - 1):
	(r, id) = input().split()
	id = int(id)
	if r == 'L':
		mi -= 1
		a[id] = mi
	elif r == 'R':
		ma += 1
		a[id] = ma
	else:
		print(min(a[id] - mi, ma - a[id]))


q = int(input())
l = 0
r = 1
pos = [0 for i in range(200000 + 5)]
for _ in range(q):
	c = list(input().split(' '))
	c[1] = int(c[1])
	if c[0] == 'L':
		pos[c[1]] = l
		l -= 1
	elif c[0] == 'R':
		pos[c[1]] = r
		r += 1
	else:
		print(min(pos[c[1]] - l, r - pos[c[1]]) - 1)


def min(a, b):
	if a < b:
		return a
	return b
pos = {}
l = 1
r = 0
n = int(input())
while n > 0:
	n -= 1
	read = input().split(' ')
	m = str(read[0])
	p = str(read[1])
	if m == 'L':
		l -= 1
		pos[p] = l
	elif m == 'R':
		r += 1
		pos[p] = r
	else:
		print(min(pos[p] - l, r - pos[p]))


p = input()
a = [0] * 200001
r = 1
l = 0
i = 1
while i <= int(p):
	MainInput = input().split(' ')
	x = MainInput[0]
	m = int(MainInput[1])
	if x == 'R':
		a[m] = r
		r += 1
	elif x == 'L':
		a[m] = l
		l -= 1
	elif x == '?':
		print(min(a[m] - l - 1, r - a[m] - 1))
	i += 1


q = int(input())
l = 0
r = 0
all_ = 0
arr = [0] * (1000000 * 2)
pos = [0] * 1000000
for i in range(q):
	s = input().split()
	id_ = int(s[1])
	op = s[0]
	if op == 'L':
		if all_ == 0:
			l = 1000001
			r = l + 1
		arr[l] = id_
		pos[id_] = l
		l -= 1
		all_ += 1
	if op == 'R':
		if all_ == 0:
			r = 1000001
			l = r - 1
		arr[r] = id_
		pos[id_] = r
		r += 1
		all_ += 1
	if op == '?':
		print(min(pos[id_] - l, r - pos[id_]) - 1)


import sys
input = sys.stdin.readline
t = int(input())
(l, r) = (0, 0)
d = [0] * (pow(10, 5) * 2)
d += [0]
a = input().split()
(x, y) = (str(a[0]), int(a[1]))
d[y] = l
l -= 1
r += 1
t -= 1
while t:
	t -= 1
	a = input().split()
	(x, y) = (str(a[0]), int(a[1]))
	if x == 'L':
		d[y] = l
		l -= 1
	elif x == 'R':
		d[y] = r
		r += 1
	else:
		print(min(abs(d[y] - l), abs(d[y] - r)) - 1)


import sys
import io, os
input = sys.stdin.buffer.readline
q = int(input())

class BIT:

	def __init__(self, n):
		self.n = n
		self.bit = [0] * (self.n + 1)

	def init(self, init_val):
		for (i, v) in enumerate(init_val):
			self.add(i, v)

	def add(self, i, x):
		i += 1
		while i <= self.n:
			self.bit[i] += x
			i += i & -i

	def sum(self, i, j):
		return self._sum(j) - self._sum(i)

	def _sum(self, i):
		res = 0
		while i > 0:
			res += self.bit[i]
			i -= i & -i
		return res

	def lower_bound(self, x):
		s = 0
		pos = 0
		depth = self.n.bit_length()
		v = 1 << depth
		for i in range(depth, -1, -1):
			k = pos + v
			if k <= self.n and s + self.bit[k] < x:
				s += self.bit[k]
				pos += v
			v >>= 1
		return pos
maxn = 2 * 10 ** 5 + 50
bit = BIT(2 * maxn + 1)
d = {}
for i in range(q):
	(t, id) = map(str, input().split())
	t = t[2:3]
	id = id[2:-1]
	id = int(id)
	if t == 'L':
		d[id] = -i + maxn
		bit.add(-i + maxn, 1)
	elif t == 'R':
		d[id] = i + maxn
		bit.add(i + maxn, 1)
	else:
		j = d[id]
		ans = min(bit.sum(j + 1, bit.n), bit.sum(0, j))
		print(ans)


def prog():
	from sys import stdin
	q = int(stdin.readline())
	pos = [0 for i in range(200020)]
	(l, r) = (-1, 1)
	(y, x) = stdin.readline().split()
	for i in range(1, q):
		(y, x) = stdin.readline().split()
		x = int(x)
		if y == 'L':
			pos[x] = l
			l -= 1
		elif y == 'R':
			pos[x] = r
			r += 1
		else:
			print(min(abs(pos[x] - l), abs(pos[x] - r)) - 1)
prog()


q = int(input())
lm = 0
rm = 0
idx = {}
ans = []
for i in range(q):
	(c, id) = [s for s in input().split()]
	if i == 0:
		idx[id] = 0
	elif c == 'L':
		lm -= 1
		idx[id] = lm
	elif c == 'R':
		rm += 1
		idx[id] = rm
	elif c == '?':
		ans.append(min(idx[id] - lm, rm - idx[id]))
print(*ans, sep='\n')


import sys
input = sys.stdin.readline
qq = int(input())
l = []
r = []
q = []
for _ in range(qq):
	(t, i) = input().split()
	i = int(i)
	if t == 'L':
		l.append(i - 1)
	elif t == 'R':
		r.append(i - 1)
	else:
		q.append((len(l), len(r), i - 1))
x = list(reversed(l)) + r
a = [0] * 200000
n = len(l)
m = len(r)
for i in range(len(x)):
	a[x[i]] = i
for (l, r, i) in q:
	print(min(a[i] - n + l, n + r - a[i] - 1))


n = int(input())
L = [0] * (n + 1)
R = [0] * (n + 1)
S = [0] * (n + 1)
d = dict()
A = [0] * (n + 1)
for j in range(1, n + 1):
	(c, val) = input().split()
	A[j] = [c, int(val)]
	val = int(val)
	if c == 'L':
		S[j] = 1 + S[j - 1]
		L[j] = 1 + L[j - 1]
		R[j] = R[j - 1]
		d[val] = j
	elif c == 'R':
		S[j] = 1 + S[j - 1]
		L[j] = L[j - 1]
		R[j] = 1 + R[j - 1]
		d[val] = j
	else:
		S[j] = S[j - 1]
		L[j] = L[j - 1]
		R[j] = R[j - 1]
		ints = d[val]
		left = L[j] - L[ints]
		right = R[j] - R[ints]
		sums = S[ints] - 1
		if A[ints][0] == 'L':
			print(min(left, right + sums))
		if A[ints][0] == 'R':
			print(min(right, left + sums))


def go():
	n = int(input())
	r = 1
	l = -1
	(_, i) = input().split(' ')
	k = {i: 0}
	for i in range(n - 1):
		(position, i) = input().split(' ')
		if position == 'R':
			k[i] = r
			r += 1
		elif position == 'L':
			k[i] = l
			l -= 1
		else:
			print(min(-(l + 1) + k[i], r - k[i] - 1))
	return
go()


import sys
q = int(input())
(l, r) = (-1, 1)
pos = [0] * 200001
k = 0
for line in sys.stdin:
	(t, a) = line.split()
	a = int(a)
	if k == 0:
		pos[a] = 0
	elif t == 'L':
		pos[a] = l
		l -= 1
	elif t == 'R':
		pos[a] = r
		r += 1
	else:
		print(min(abs(pos[a] - l), abs(pos[a] - r)) - 1)
	k += 1


n = int(input())
import collections
left = 0
right = 0
first = True
sootv = {}
ans = []
for i in range(n):
	a = input().split()
	if a[0] == 'L':
		left -= 1
		sootv[a[1]] = left
	elif a[0] == 'R':
		right += 1
		sootv[a[1]] = right
	else:
		kk = sootv[a[1]]
		ans.append(str(min(kk - left, right - kk)))
	if first:
		first = False
		left = 0
		right = 0
		if a[1] in sootv:
			sootv[a[1]] = 0
print('\n'.join(ans))


def main():
	shelf = [0] * (2 * 10 ** 5 + 1)
	(curr_l, curr_r) = (0, 0)
	num_queries = int(input())
	answers = []
	for q in range(num_queries):
		(query_type, book_idx) = input().split()
		book_idx = int(book_idx)
		if q == 0:
			shelf[book_idx] = curr_l
			curr_l -= 1
			curr_r += 1
		elif query_type == 'L':
			shelf[book_idx] = curr_l
			curr_l -= 1
		elif query_type == 'R':
			shelf[book_idx] = curr_r
			curr_r += 1
		else:
			pos = shelf[book_idx]
			count = min(pos - curr_l, curr_r - pos) - 1
			answers.append(count)
	for ans in answers:
		print(ans)
main()


n = int(input())
d = {}
l = 0
r = 0
for i in range(n):
	s = input().split()
	if s[0] == 'R':
		d[s[1]] = [1, r]
		r += 1
	if s[0] == 'L':
		d[s[1]] = [0, l]
		l += 1
	if s[0] == '?':
		if d[s[1]][0] == 0:
			print(min(l - d[s[1]][1] - 1, d[s[1]][1] + r))
		else:
			print(min(r - d[s[1]][1] - 1, l + d[s[1]][1]))


from sys import stdin, stdout
indices = {}
(l, r) = (1, 0)
for _ in range(int(stdin.readline())):
	(a, b) = stdin.readline().split()
	if a == 'R':
		indices[int(b)] = r + 1
		r += 1
	elif a == 'L':
		indices[int(b)] = l - 1
		l -= 1
	else:
		stdout.write(str(min(indices[int(b)] - l, r - indices[int(b)])) + '\n')


from sys import stdin
input = stdin.readline

def main():
	n = int(input())
	all_L = 0
	all_R = 0
	pos_L = {}
	pos_R = {}
	for _ in range(n):
		(pos, val) = input().split()
		if pos == 'L':
			all_L += 1
			pos_L[val] = all_L
		elif pos == 'R':
			all_R += 1
			pos_R[val] = all_R
		elif val in pos_L:
			print(min(all_L - pos_L[val], all_R + pos_L[val] - 1))
		else:
			print(min(all_R - pos_R[val], all_L + pos_R[val] - 1))
main()


(right, left) = (0, 1)
d = {}
for _ in [0] * int(input()):
	(letter, number) = input().split()
	if letter == 'L':
		left -= 1
		d[int(number)] = left
	elif letter == 'R':
		right += 1
		d[int(number)] = right
	else:
		print(min(d[int(number)] - left, right - d[int(number)]))


import sys
input = sys.stdin.readline
q = int(input())
right = []
right_s = set()
l_right = 0
left = []
left_s = set()
l_left = 0
l = 0
for i in range(q):
	(char, n) = input().split()
	numb = int(n)
	if char == 'L':
		left.append(numb)
		left_s.add(numb)
		l_left += 1
	elif char == 'R':
		right.append(numb)
		right_s.add(numb)
		l_right += 1
	elif numb in right_s:
		z = right.index(numb)
		if l_left != 0:
			print(min(l_right - z - 1, l_left + z))
		else:
			print(min(l_right - z - 1, z))
	else:
		z = left.index(numb)
		if l_right != 0:
			print(min(l_left - z - 1, l_right + z))
		else:
			print(min(l_left - z - 1, z))


p = input()
a = [0] * 2000000
h = []
r = 1
l = 0
i = 1
while i <= int(p):
	MainInput = input().split(' ')
	x = MainInput[0]
	m = int(MainInput[1])
	if x == 'R':
		a[m] = r
		r += 1
	elif x == 'L':
		a[m] = l
		l -= 1
	elif x == '?':
		h.append(min(a[m] - l - 1, r - a[m] - 1))
	i += 1
for x in range(len(h)):
	print(h[x])


q = int(input())
pos = {}
lt = 0
rt = lt - 1
for _ in range(q):
	(t, i) = input().split()
	if t == 'L':
		lt -= 1
		pos[i] = lt
	elif t == 'R':
		rt += 1
		pos[i] = rt
	else:
		print(min(pos[i] - lt, rt - pos[i]))


import sys
q = int(sys.stdin.readline())
Q = [sys.stdin.readline().split() for i in range(q)]
Lcount = 0
Rcount = 0
BOOK = [None] * (2 * 10 ** 5 + 1)
for i in range(q):
	if Q[i][0] == 'L':
		Lcount += 1
		BOOK[int(Q[i][1])] = ('L', Lcount, Rcount)
	elif Q[i][0] == 'R':
		Rcount += 1
		BOOK[int(Q[i][1])] = ('R', Lcount, Rcount)
	else:
		l = BOOK[int(Q[i][1])][1]
		r = BOOK[int(Q[i][1])][2]
		if BOOK[int(Q[i][1])][0] == 'R':
			ANS = min(Rcount - r, Lcount - l + (r + l - 1))
		elif BOOK[int(Q[i][1])][0] == 'L':
			ANS = min(Lcount - l, Rcount - r + (r + l - 1))
		sys.stdout.write(str(ANS) + '\n')


(l, r) = (1, 0)
d = {}
for _ in range(int(input())):
	(letter, id) = input().split()
	if letter == 'L':
		l -= 1
		d[id] = l
	elif letter == 'R':
		r += 1
		d[id] = r
	else:
		print(min(d[id] - l, r - d[id]))


n = int(input())
(ir, pnob) = (0, 0)
queries = []
shelf = dict()
for i in range(n):
	query = list(input().split())
	query[1] = int(query[1])
	queries.append(query)
for query in queries:
	if query[0] == 'L':
		shelf[query[1]] = ir
		ir -= 1
		pnob += 1
	elif query[0] == 'R':
		shelf[query[1]] = pnob + ir + 1
		pnob += 1
	else:
		pos = shelf[query[1]] + abs(ir)
		print(min(abs(pos - 1), abs(pnob - pos)))


import sys

def minp():
	return sys.stdin.readline().strip()
a = [0] * (2 * 10 ** 5)
w = [0] * (2 * 10 ** 5 + 1)
q = int(minp())
l = 0
r = 0
for i in range(q):
	(c, id) = minp().split()
	id = int(id)
	if c == 'L':
		l -= 1
		if l < 0:
			l = 199999
		a[l] = id
		w[id] = l
	elif c == 'R':
		a[r] = id
		w[id] = r
		r += 1
		if r == 200000:
			r = 0
	else:
		print(min((w[id] - l + 400000) % 200000, (r - w[id] - 1 + 400000) % 200000))


q = int(input())
left = [[] for x in range(10 ** 6)]
l = -1
r = 0
right = []
Q = []
for _ in range(q):
	query = input().split()
	Q.append(query)
for i in range(q):
	query = Q[i]
	query[1] = int(query[1])
	if query[0] == 'L':
		left[query[1]] = l
		l -= 1
	elif query[0] == 'R':
		left[query[1]] = r
		r += 1
	else:
		j = left[query[1]]
		print(min(j - l - 1, r - j - 1))


q = int(input())
d = {}
l = 0
r = 0
s = 0
for _ in range(q):
	(cmd, id) = input().split()
	if cmd == 'L':
		l -= 1
		d[id] = l
	elif cmd == 'R':
		r += 1
		d[id] = r - 1
	else:
		print(min(r - d[id] - 1, d[id] - l))


q = int(input())
data = []
for _ in range(q):
	data.append(input().split())
l = 0
r = 1
b = [-1 for i in range(200007)]
for i in data:
	id = int(i[1])
	if i[0] == 'L':
		b[id] = l
		l -= 1
	if i[0] == 'R':
		b[id] = r
		r += 1
	if i[0] == '?':
		p = b[id]
		print(min(p - l - 1, r - p - 1))


import math

def distance(a, b):
	return math.sqrt(a ** 2 + b ** 2)
cases = int(input())
dictionary = {}
left = 10000
right = 10000
for _ in range(cases):
	val = input().split(' ')
	if val[0] == 'L':
		dictionary[val[1]] = left
		left -= 1
		if right == 10000:
			right += 1
	elif val[0] == 'R':
		dictionary[val[1]] = right
		right += 1
		if left == 10000:
			left -= 1
	else:
		index = dictionary.get(val[1])
		res_right = abs(right - index - 1)
		res_left = abs(index - left - 1)
		print(min(res_left, res_right))


(l, r) = (1, 0)
d = {}
for _ in [0] * int(input()):
	(o, i) = input().split()
	if o == 'L':
		l -= 1
		d[i] = l
	elif o == 'R':
		r += 1
		d[i] = r
	else:
		print(min(d[i] - l, r - d[i]))


n = int(input())
booklist = {}
a = input().split()
booklist[a[1]] = 0
left = 0
right = 0
for i in range(n - 1):
	a = input().split()
	if a[0] == 'L':
		left -= 1
		booklist[a[1]] = left
	elif a[0] == 'R':
		right += 1
		booklist[a[1]] = right
	else:
		print(min(booklist[a[1]] - left, right - booklist[a[1]]))


import sys
f = sys.stdin
out = sys.stdout
q = int(f.readline().rstrip('\r\n'))
(pos, id) = f.readline().rstrip('\r\n').split()
mid = int(id)
left = []
right = []
dleft = {}
dright = {}
for i in range(q - 1):
	(pos, id) = f.readline().rstrip('\r\n').split()
	id = int(id)
	if pos == 'L':
		left.append(id)
		dleft[id] = len(dleft) + 1
	elif pos == 'R':
		right.append(id)
		dright[id] = len(dright) + 1
	elif id == mid:
		out.write(str(min(len(dleft), len(dright))) + '\n')
	elif id in dleft:
		z = len(dleft) - dleft[id] + 1
		out.write(str(min(z - 1, 1 + len(dright) + dleft[id] - 1)) + '\n')
	else:
		z = dright[id]
		out.write(str(min(len(dleft) + z, len(dright) - z)) + '\n')


n = int(input())
lib = {}
idL = 0
idR = -1
for i in range(n):
	masukan = input().split(' ')
	if masukan[0] == 'L':
		idL = idL - 1
		lib[masukan[1]] = idL
	elif masukan[0] == 'R':
		idR = idR + 1
		lib[masukan[1]] = idR
	else:
		idx = lib[masukan[1]]
		idxx = idx + abs(idL)
		print(min(idxx, abs(idR + abs(idL) - idxx)))


input = __import__('sys').stdin.readline
q = int(input())
d = {}
(l, r) = (0, 1)
for i in range(q):
	(a, b) = map(str, input().split())
	b = int(b)
	if a == 'L':
		d[b] = l
		l -= 1
	elif a == 'R':
		d[b] = r
		r += 1
	else:
		ans = min(abs(r - d[b]), abs(d[b] - l))
		print(ans - 1)


n = int(input())
l = {}
c1 = 0
c2 = 0
for i in range(n):
	d = list(input().split())
	if d[0] == 'L':
		l[d[1]] = [c1, c2, 0]
		c1 += 1
	elif d[0] == 'R':
		l[d[1]] = [c1, c2, 1]
		c2 += 1
	elif l[d[1]][2] == 0:
		print(min(c1 - l[d[1]][0] - 1, l[d[1]][0] + c2))
	else:
		print(min(c2 - l[d[1]][1] - 1, l[d[1]][1] + c1))


t = int(input())
d = dict()
(m, n) = input().split()
n = int(n)
d[n] = 0
lft = 0
rgt = 0
for i in range(t - 1):
	(m, n) = input().split()
	n = int(n)
	if m == 'L':
		lft = lft - 1
		d[n] = lft
	elif m == 'R':
		rgt = rgt + 1
		d[n] = rgt
	else:
		v = d[n]
		g = v - lft
		k = rgt - v
		mx = min(g, k)
		print(mx)


import sys
input = lambda : sys.stdin.readline()
MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : list(map(int, input().split()))
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
n = ii()
l = [[10 ** 6, -10 ** 6] for i in range(2 * 10 ** 5 + 2)]
(iL, iR) = (0, 1)
for _ in range(n):
	(a, b) = input().split()
	if a == 'L':
		l[int(b) - 1][0] = min(iL, l[int(b) - 1][0])
		l[int(b) - 1][1] = max(iL, l[int(b) - 1][1])
		iL -= 1
	elif a == 'R':
		l[int(b) - 1][0] = min(iR, l[int(b) - 1][0])
		l[int(b) - 1][1] = max(iR, l[int(b) - 1][1])
		iR += 1
	else:
		print(min(l[int(b) - 1][0] - iL - 1, iR - l[int(b) - 1][1] - 1))


q = int(input())
tl = []
tr = []
t_len = 2 * 10 ** 5 + 1
t = []
for x in range(0, t_len, +1):
	t.append([0, ''])
for x in range(0, q, +1):
	tmp_tab = str(input()).split(' ')
	l = tmp_tab[0]
	c = int(tmp_tab[1])
	if l == 'L':
		t[c][0] = len(tl) + 1
		t[c][1] = 'L'
		tl.append(c)
	elif l == 'R':
		t[c][0] = len(tr) + 1
		t[c][1] = 'R'
		tr.append(c)
	elif t[c][1] == 'L':
		print(min(len(tl) - t[c][0], len(tr) + t[c][0] - 1))
	else:
		print(min(len(tl) + t[c][0] - 1, len(tr) - t[c][0]))


TOT = 2 * 10 ** 5
a = [-1] * (TOT + 1)
q = int(input())
fp = input().split()
a[int(fp[1])] = 0
L = -1
R = 1
for _ in range(q - 1):
	qq = input().split()
	pos = int(qq[1])
	if qq[0] == 'L':
		a[pos] = L
		L -= 1
	elif qq[0] == 'R':
		a[pos] = R
		R += 1
	else:
		print(min(a[pos] - L - 1, R - a[pos] - 1))


n = int(input())
a = [0] * 200001
l = 0
r = 1
for i in range(n):
	(lang, d) = input().split()
	d = int(d)
	if lang == 'R':
		a[d] = r
		r += 1
	elif lang == 'L':
		a[d] = l
		l -= 1
	else:
		m = min(a[d] - l - 1, r - a[d] - 1)
		print(m)


q = int(input())
(L, R, nums) = ([], [], [])
for _ in range(q):
	line = input()
	(v, a) = (line.split()[0], int(line.split()[1]))
	if v == 'L':
		L.append(a)
	elif v == 'R':
		R.append(a)
	else:
		nums.append([len(L), len(R), a])
(all_nl, all_nr) = (len(L), len(R))
L.reverse()
A = L + R
maps = {a: i for (i, a) in enumerate(A)}
for num in nums:
	(l, r, a) = (num[0], num[1], num[2])
	(nl, nr) = (maps[a], len(A) - maps[a] - 1)
	(zl, zr) = (all_nl - l, all_nr - r)
	print(min(nl - zl, nr - zr))


q = int(input())
freq_id = dict()
start = 0
end = 1
for i in range(q):
	(qi, di) = input().split()
	di = int(di)
	if qi == 'L':
		freq_id[di] = start
		start -= 1
	elif qi == 'R':
		freq_id[di] = end
		end += 1
	else:
		print(min(freq_id[di] - start - 1, end - freq_id[di] - 1))


cntl = 0
cntr = 0
d = []
ccnt = []
n = int(input())
for i in range(2000005):
	d.append(0)
	ccnt.append(0)
for i in range(n):
	(c, x) = input().split()
	x = int(x)
	if c == 'R':
		d[x] = cntr + cntl
		cntr += 1
		ccnt[x] = cntl
	elif c == 'L':
		d[x] = 0
		cntl += 1
		ccnt[x] = cntl
	else:
		r = d[x] + cntl - ccnt[x]
		r += 1
		print(min(r - 1, cntr + cntl - r))


m = [0] * (2 * 10 ** 5 + 1)
n = int(input())
input().split()
l = -1
r = 1
for i in range(n - 1):
	(p, b_id) = input().split()
	b_id = int(b_id)
	if p == 'L':
		m[b_id] = l
		l -= 1
	elif p == 'R':
		m[b_id] = r
		r += 1
	elif p == '?':
		print(int(min(r - m[b_id], m[b_id] - l) - 1))


from sys import stdin
from collections import deque
n = int(input())
d = dict()
y = 0
s = deque()
aux = stdin.readline().strip().split()
s.append(int(aux[1]))
d.update({int(aux[1]): 0})
l = 1
for i in range(1, n):
	aux = stdin.readline().strip().split()
	x = int(aux[1])
	if aux[0] == 'L':
		y += 1
		d.update({x: 0 - y})
		l += 1
	elif aux[0] == 'R':
		d.update({x: l - y})
		l += 1
	else:
		q = d[x] + y
		print(min(q, l - 1 - q))


n = int(input())
d = {}
l = 0
r = 1
for _ in range(n):
	(command, num) = input().split()
	if command == 'L':
		d[num] = l
		l -= 1
	elif command == 'R':
		d[num] = r
		r += 1
	else:
		print(min(d[num] - l - 1, r - 1 - d[num]))


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import Counter
import heapq
from collections import Counter
d = {}
l = 0
r = 0
le = 0
for _ in range(int(input())):
	s = input().split()
	if s[0] == '?':
		var = d[int(s[1])]
		if var[3] == 'L':
			ans = min(var[2] + r - var[1], l - var[0] - 1)
		else:
			ans = min(var[2] + l - var[0], r - var[1] - 1)
		print(ans)
	elif s[0] == 'L':
		d[int(s[1])] = (l, r, le, 'L')
		le += 1
		l += 1
	else:
		d[int(s[1])] = (l, r, le, 'R')
		le += 1
		r += 1


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
N = 2 * 10 ** 5 + 1
n = I()
l = N - 1
r = N + 1
v = [0] * N
v[int(S().split()[-1])] = N
for i in range(n - 1):
	s = S().split()
	if s[0] == 'L':
		v[int(s[-1])] = l
		l -= 1
	elif s[0] == 'R':
		v[int(s[-1])] = r
		r += 1
	else:
		id = v[int(s[-1])]
		print(min(abs(l + 1 - id), abs(r - 1 - id)))


n = int(input())
ml = 0
mr = 1
a = [0] * 200001
for i in range(n):
	(L, d) = input().split()
	d = int(d)
	if L == 'L':
		a[d] = ml
		ml -= 1
	elif L == 'R':
		a[d] = mr
		mr += 1
	else:
		print(min(a[d] - ml - 1, mr - a[d] - 1))


import sys
total = sys.stdin.readline()
query = sys.stdin.readlines()
count = [0] * 200005
(left, right) = (0, 1)
for _ in range(int(total)):
	s = query[_].split()
	(way, num) = (s[0], int(s[1]))
	if way == 'L':
		count[num] = left
		left = left - 1
	elif way == 'R':
		count[num] = right
		right = right + 1
	elif way == '?':
		print(min(count[num] - left - 1, right - count[num] - 1))


q = int(input())
a = [0 for i in range(2 * 10 ** 5 + 1)]
base = 0
l = -1
r = 1
input()
k = 0
for i in range(q - 1):
	s = input().split()
	b = int(s[1])
	if s[0] == 'L':
		a[b] = l
		l -= 1
		base += 1
		k += 1
	elif s[0] == 'R':
		a[b] = r
		r += 1
		k += 1
	else:
		ind = a[b] + base
		print(min(ind, k - ind))


n = int(input())
ptr1 = 1
ptr2 = 1
L = {}
R = {}
for i in range(n):
	query = input().split()
	if query[0] == 'L':
		L[query[1]] = ptr1
		ptr1 += 1
	elif query[0] == 'R':
		R[query[1]] = ptr2
		ptr2 += 1
	else:
		try:
			if L[query[1]] > 0:
				temp = L[query[1]]
				if ptr2 + temp - 2 < ptr1 - temp - 1:
					print(ptr2 + temp - 2)
				else:
					print(ptr1 - temp - 1)
		except:
			pass
		try:
			if R[query[1]] > 0:
				temp = R[query[1]]
				if ptr1 + temp - 2 < ptr2 - temp - 1:
					print(ptr1 + temp - 2)
				else:
					print(ptr2 - temp - 1)
		except:
			pass


arr = dict()
pivot = 0
inside = 0
prev1 = 0
prev2 = 0
(l, r) = (-1, -1)
for Q in range(int(input())):
	(q, n) = input().split()
	n = int(n)
	if l == -1 and r == -1:
		inside += 1
		(l, r) = (n, n)
		arr[n] = prev1
	elif q == 'R':
		r = n
		inside += 1
		arr[n] = prev2 + 1
		prev2 += 1
	elif q == 'L':
		l = n
		inside += 1
		arr[n] = prev1 - 1
		prev1 -= 1
	else:
		print(min(arr[r] - arr[n], arr[n] - arr[l]))


n = int(input())
l = []
r = []
a = [0] * 200001
l1 = 0
r1 = 0
k = 1
for i in range(n):
	s = input()
	if s[0] == 'R':
		r1 += 1
		r.append(r1)
		l.append(0)
		a[int(s[2:len(s)])] = k
		k += 1
	elif s[0] == 'L':
		l1 += 1
		l.append(l1)
		r.append(0)
		a[int(s[2:len(s)])] = k
		k += 1
	else:
		d = int(s[2:len(s)])
		if l[a[d] - 1] != 0:
			c = l1 - l[a[d] - 1]
		else:
			c = r1 - r[a[d] - 1]
		if c >= l1 + r1 - c - 1:
			print(l1 + r1 - c - 1)
		else:
			print(c)


n = int(input())
d = {}
matr = [0] * (2 * n + 1)
head = n - 1
tail = n
for i in range(n):
	(st, n) = input().split()
	n = int(n)
	if st == 'L':
		matr[head] = n
		d[n] = head
		head -= 1
	elif st == 'R':
		matr[tail] = n
		d[n] = tail
		tail += 1
	else:
		print(min(d[n] - head, tail - d[n]) - 1)


from collections import deque
from collections import defaultdict
d = defaultdict()
l = 0
r = 0
start = end = 0
for i in range(int(input())):
	(n, m) = input().split()
	m = int(m)
	if i == 0:
		d[m] = [0, 0]
		r += 1
		l -= 1
		continue
	if n == 'L':
		d[m] = [l, 0]
		l -= 1
		start -= 1
	elif n == 'R':
		d[m] = [0, r]
		r += 1
		end += 1
	else:
		if d[m][0] == 0 and d[m][1] == 0:
			ans = min(abs(start), end)
		elif d[m][0] == 0:
			ans = min(abs(d[m][1] - end), abs(d[m][1]) + abs(start))
		else:
			ans = min(abs(d[m][0] - start), abs(d[m][0]) + end)
		print(ans)


f"{(lambda sys, b, l, r: (lambda bs, ls, rs, q: [(lambda c, i: (lambda i: [bs(i, l[0]), ls(0, l[0] - 1)] if c == 'L' else [rs(0, r[0] + 1), bs(i, r[0])] if c == 'R' else print(min(b[i] - l[0] - 1, r[0] - b[i])))(int(i)))(*s.split()) for s in sys.stdin])(b.__setitem__, l.__setitem__, r.__setitem__, sys.stdin.readline()))(__import__('sys'), [0] * 200200, [0], [0])}"


s = [0] * 200000
d = {}
r = 1
l = -1
a = []
t = int(input())
s[0] = input().split()[1]
d[s[0]] = 0
for x in range(t - 1):
	(q, n) = input().split()
	if q == 'L':
		s[l] = n
		d[n] = l
		l -= 1
	if q == 'R':
		s[r] = n
		d[n] = r
		r += 1
	if q == '?':
		a += [str(d[n] - l - 1) if d[n] - l < r - d[n] else str(r - d[n] - 1)]
print('\n'.join(a))


from sys import stdin
from collections import *

def arr_inp(n):
	if n == 1:
		return [int(x) for x in stdin.readline().split()]
	elif n == 2:
		return [float(x) for x in stdin.readline().split()]
	else:
		return list(stdin.readline().split())
(left, right, mem) = (0, 0, defaultdict(list))
for i in range(int(input())):
	(s, n) = arr_inp(3)
	n = int(n)
	if s == 'L':
		left += 1
		mem[n] = [left, 'L']
	elif s == 'R':
		right += 1
		mem[n] = [right, 'R']
	else:
		mi = 0
		if mem[n][1] == 'L':
			mi = min(left - mem[n][0], mem[n][0] - 1 + right)
		else:
			mi = min(right - mem[n][0], mem[n][0] - 1 + left)
		print(mi)


import sys

class Input:

	def __init__(self):
		self.fh = sys.stdin

	def get_next_line(self):
		while True:
			line = sys.stdin.readline()
			if line == '\n':
				continue
			return line

	def next_line_ints(self):
		line = self.get_next_line()
		return [int(item) for item in line.split()]

	def next_line_strs(self):
		line = self.get_next_line()
		return [str(item) for item in line.split()]

class INput:

	def __init__(self):
		self.fh = sys.stdin

	def get_next_line(self):
		while True:
			line = sys.stdin.readline()
			if line == '\n':
				continue
			return line

	def next_line_ints(self):
		line = self.get_next_line()
		return [int(item) for item in line.split()]

	def next_line_strs(self):
		line = self.get_next_line()
		return line.split()
In = INput()
_ = In.next_line_ints()[0]
leftmost = dict()
rightmost = dict()
leftid = 0
rightid = 0
for item in range(_):
	(order, oper) = In.next_line_strs()
	oper = int(oper)
	if order == 'L':
		leftmost[oper] = leftid
		leftid += 1
	elif order == 'R':
		rightmost[oper] = rightid
		rightid += 1
	elif order == '?':
		dis_right = -1
		dis_left = -1
		if oper in leftmost:
			ans = leftmost[oper]
			dis_left = leftid - ans - 1
			dis_right = ans + rightid
			print(min(dis_left, dis_right))
			continue
		ans = rightmost[oper]
		dis_right = rightid - ans - 1
		dis_left = ans + leftid
		print(min(dis_left, dis_right))


n = int(input())
ln = 0
rn = 0
ids = {}
bel = {}
for i in range(n):
	s = input().split()
	op = s[0]
	id = int(s[1])
	if op == 'L' or op == 'R':
		if op == 'L':
			ln += 1
			ids[id] = ln
			bel[id] = 'l'
		else:
			rn += 1
			ids[id] = rn
			bel[id] = 'r'
	elif bel[id] == 'l':
		l = ln - ids[id]
		r = ids[id] + rn - 1
		print(min(l, r))
	else:
		r = rn - ids[id]
		l = ids[id] + ln - 1
		print(min(l, r))


import sys
import math
n = int(input())
pos = [0] * (2 * 10 ** 5 + 1)
(l, r) = (0, 0)
for i in range(n):
	(a, b) = map(str, input().split())
	id = int(b)
	if i == 0:
		pos[id] += 0
		l -= 1
		r += 1
	elif a == 'L':
		pos[id] += l
		l -= 1
	elif a == 'R':
		pos[id] += r
		r += 1
	else:
		print(min(abs(pos[id] - l), abs(pos[id] - r)) - 1)


import re
import sys
exit = sys.exit
from bisect import bisect_left as bsl, bisect_right as bsr
from collections import Counter, defaultdict as ddict, deque
from functools import lru_cache
cache = lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum = enumerate
ri = lambda : int(rln())
ris = lambda : list(map(int, rfs()))
rln = sys.stdin.readline
rl = lambda : rln().rstrip('\n')
rfs = lambda : rln().split()
mod = 1000000007
d4 = [(0, -1), (1, 0), (0, 1), (-1, 0)]
d8 = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
q = ri()
(l, r) = (0, 1)
d = {}
for _ in range(q):
	(typ, id) = rfs()
	if typ == 'L':
		d[id] = l
		l -= 1
	elif typ == 'R':
		d[id] = r
		r += 1
	else:
		i = d[id]
		print(min(i - l, r - i) - 1)


start = 0
hm = {}
lm = 0
rm = 0
cbook = 0
q = int(input())
for __ in range(q):
	(qt, idb) = input().split()
	if qt == 'L':
		if cbook == 0:
			hm[idb] = 0
			cbook = 1
		else:
			lm -= 1
			hm[idb] = lm
	elif qt == 'R':
		if cbook == 0:
			hm[idb] = 0
			cbook = 1
		else:
			rm += 1
			hm[idb] = rm
	elif qt == '?':
		bi = hm[idb]
		print(min(bi - lm, rm - bi))


s = []
q = {}
(l, r) = (0, 0)
for i in range(int(input())):
	(a, b) = map(str, input().split())
	if i == 0:
		q[b] = 0
	elif a == 'R':
		r += 1
		q[b] = r
	elif a == 'L':
		l -= 1
		q[b] = l
	elif a == '?':
		s.append(min(q[b] - l, r - q[b]))
print(*s, sep='\n')


import os, sys
from collections import defaultdict, Counter, deque
from io import BytesIO, IOBase
from math import gcd, ceil

def lcm(a, b):
	return a * b // gcd(a, b)
MAXN = 100001
spf = [0 for i in range(MAXN)]

def getFactorization(x):
	ret = list()
	while x != 1:
		ret.append(spf[x])
		x = x // spf[x]
	return ret

def main():
	pos = [0] * 2000000
	(up, do) = (1, 0)
	for _ in range(int(input())):
		(a, b) = input().split()
		if a == 'L':
			up -= 1
			pos[int(b)] = up
		elif a == 'R':
			do += 1
			pos[int(b)] = do
		else:
			print(min(pos[int(b)] - up, do - pos[int(b)]))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import collections
import sys
elems = {}
(l, r) = (-1, 1)
queries = []
lines = sys.stdin.readlines()
q = int(lines[0].strip())
queries = lines[1:]
for i in range(q):
	[queryType, index] = queries[i].strip().split()
	index = int(index)
	if queryType == 'L':
		elems[index] = l
		l -= 1
	elif queryType == 'R':
		elems[index] = r
		r += 1
	else:
		dex = elems[index]
		if dex > 0:
			ans1 = r - dex - 1
			ans2 = dex - l - 1 - 1
		else:
			ans1 = r - dex - 1 - 1
			ans2 = dex - l - 1
		print(min(ans1, ans2))


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from heapq import *
from math import gcd, factorial, floor, ceil
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for pp in range(t):
		solve(pp)

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def google(p):
	print('Case #' + str(p) + ': ', end='')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
inf = pow(10, 20)
mod = 998244353

def solve(case):
	id = 0
	mx = 1
	mn = -1
	mapper = {}
	q = int(inp())
	(typ, num) = strsep()
	num = int(num)
	mapper[num] = id
	for i in range(q - 1):
		(typ, num) = strsep()
		num = int(num)
		if typ == 'L':
			mapper[num] = mn
			mn -= 1
		elif typ == 'R':
			mapper[num] = mx
			mx += 1
		else:
			find = mapper[num]
			print(min(mx - find, find - mn) - 1)
testcase(1)


q = int(input())
(x, y) = (1, 0)
D = {}
for i in range(q):
	(a, b) = map(str, input().split())
	if a == 'L':
		x -= 1
		D[b] = x
	elif a == 'R':
		y += 1
		D[b] = y
	else:
		print(min(D[b] - x, y - D[b]))


n = int(input())
(l, r) = (1, 0)
d = {}
i = 0
while i < n:
	a = input().split()
	x = a[0]
	y = a[1]
	if x == 'L':
		l -= 1
		d[y] = l
	elif x == 'R':
		r += 1
		d[y] = r
	else:
		print(min(d[y] - l, r - d[y]))
	i += 1


from os import path
import sys, time
from math import ceil, floor, gcd, log, log2, factorial
from collections import defaultdict, Counter, deque
from itertools import permutations
maxx = float('inf')
I = lambda : int(sys.stdin.buffer.readline())
tup = lambda : map(int, sys.stdin.buffer.readline().split())
lint = lambda : [int(x) for x in sys.stdin.buffer.readline().split()]
S = lambda : sys.stdin.readline().replace('\n', '').strip()

def grid(r, c):
	return [lint() for i in range(r)]
stpr = lambda x: sys.stdout.write(f'{x}' + '\n')
star = lambda x: print(' '.join(map(str, x)))
localsys = 0
start_time = time.time()
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
ind = [0] * 200005
(l, r) = (0, 1)
ar = [sys.stdin.readline().split() for _ in range(I())]
for i in ar:
	if i[0] == 'L':
		ind[int(i[1])] = l
		l -= 1
	elif i[0] == 'R':
		ind[int(i[1])] = r
		r += 1
	else:
		indx = ind[int(i[1])]
		print(min(indx - l - 1, r - 1 - indx))
if localsys:
	print('\n\nTime Elased :', time.time() - start_time, 'seconds')


t = input()
t = int(t)
left = 0
right = 1
pos = list(range(200005))
for i in range(t):
	(query, index) = input().split()
	index = int(index)
	if query == 'L':
		pos[index] = left
		left = left - 1
	elif query == 'R':
		pos[index] = right
		right = right + 1
	else:
		ll = pos[index] - left - 1
		rr = right - 1 - pos[index]
		print(min(ll, rr))


t = int(input())
left = 0
right = 0
arr = [0] * 200001
input()
for i in range(1, t):
	(pos, idx) = input().split(' ')
	idx = int(idx)
	if pos == 'L':
		left -= 1
		arr[idx] = left
	elif pos == 'R':
		right += 1
		arr[idx] = right
	elif pos == '?':
		ind = arr[idx]
		print(min(ind - left, right - ind))


import sys
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))
Q = inp()
d = {}
for i in range(Q):
	(a, b) = sys.stdin.readline().split()
	b = int(b)
	if i == 0:
		l = r = 0
		d[b] = 0
		continue
	if a == 'L':
		l -= 1
		d[b] = l
	elif a == 'R':
		r += 1
		d[b] = r
	else:
		now = d[b]
		print(min(now - l, r - now))


result = []
q = int(input())
pos = {}
curl = 0
curr = 0
for i in range(q):
	temp = input()
	if i == 0:
		pos[temp[2:]] = curl
		curl -= 1
		curr += 1
	elif temp[0] == 'L':
		pos[temp[2:]] = curl
		curl -= 1
	elif temp[0] == 'R':
		pos[temp[2:]] = curr
		curr += 1
	else:
		result.append(min(abs(pos[temp[2:]] - curl), abs(pos[temp[2:]] - curr)) - 1)
for i in range(len(result)):
	print(result[i])


n = int(input())
arrr = {}
mi = 0
ma = 0
(t, i) = input().split()
arrr[i] = 0
for _ in range(n - 1):
	(t, i) = input().split()
	if t == 'L':
		mi -= 1
		arrr[i] = mi
	elif t == 'R':
		ma += 1
		arrr[i] = ma
	else:
		print(min(ma - arrr[i], arrr[i] - mi))


q = int(input())
dict1 = {}
left = 0
right = 0
for i in range(q):
	(op, num) = map(str, input().split())
	if op == 'L':
		left = left + 1
		dict1[num] = 'L' + str(left)
	elif op == 'R':
		right = right + 1
		dict1[num] = 'R' + str(right)
	elif op == '?':
		output = dict1[num]
		if output[0] == 'L':
			numberL = int(output[1:])
			numberR = right + numberL - 1
			numberL = left - numberL
			p = min(numberL, numberR)
			print(p)
		if output[0] == 'R':
			numberR = int(output[1:])
			numberL = left + numberR - 1
			numberR = right - numberR
			p = min(numberL, numberR)
			print(p)


q = int(input())
n = 2 * 10 ** 5
shelf = {}
(l, r) = (0, 0)
first = True
for _ in range(q):
	(query, id) = input().split()
	id = int(id)
	if query == 'L':
		if first:
			shelf[id] = 0
			first = False
		else:
			shelf[id] = l - 1
			l -= 1
	elif query == 'R':
		if first:
			shelf[id] = 0
			first = False
		else:
			shelf[id] = r + 1
			r += 1
	else:
		print(min(abs(l - shelf[id]), abs(r - shelf[id])))


q = int(input())
max_pos = 0
min_pos = 0
pos_id = [0 for i in range(200001)]
input()
for i in range(1, q):
	(q, id) = input().split()
	id = int(id)
	if q == 'R':
		max_pos += 1
		pos_id[id] = max_pos
		continue
	elif q == 'L':
		min_pos -= 1
		pos_id[id] = min_pos
		continue
	else:
		pos = pos_id[id]
		print(min(pos - min_pos, max_pos - pos))


n = int(input())
l = 0
r = 0
ls = [0 for _ in range(200005)]
(req, id) = map(str, input().split())
id = int(id)
ls[id] = 0
for i in range(n - 1):
	(req, id) = map(str, input().split())
	id = int(id)
	if req == 'L':
		l -= 1
		ls[id] = l
	elif req == 'R':
		r += 1
		ls[id] = r
	else:
		print(min(ls[id] - l, r - ls[id]))


q = int(input())
ans = {}
(l, r) = (1, 0)
for i in range(q):
	(a, b) = input().split()
	if a == 'L':
		l -= 1
		ans[b] = l
	elif a == 'R':
		r += 1
		ans[b] = r
	else:
		print(min(ans[b] - l, r - ans[b]))


import math
cases = int(input())
dictionary = {}
left = 10000
right = 10000
for _ in range(cases):
	val = input().split(' ')
	if val[0] == 'L':
		dictionary[val[1]] = left
		left -= 1
		if right == 10000:
			right += 1
	elif val[0] == 'R':
		dictionary[val[1]] = right
		right += 1
		if left == 10000:
			left -= 1
	else:
		index = dictionary.get(val[1])
		res_right = abs(right - index - 1)
		res_left = abs(index - left - 1)
		print(min(res_left, res_right))


import os, sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import ceil
mod = 10 ** 9 + 7
for _ in range(1):
	q = int(input())
	pos = [0] * 200011
	left_count = 0
	right_count = 0
	for i in range(q):
		info = list(map(str, input().split()))
		a = int(info[1])
		if i == 0:
			pos[a] = 0
			left_count -= 1
			right_count += 1
		elif info[0] == 'R':
			pos[a] = right_count
			right_count += 1
		elif info[0] == 'L':
			pos[a] = left_count
			left_count -= 1
		else:
			ans = min(abs(pos[a] - left_count), abs(pos[a] - right_count))
			print(ans - 1)


q = int(input())
minimum = 0
maximum = -1
d = {}
for i in range(q):
	(a, b) = input().split()
	b = int(b)
	if a == 'L':
		minimum -= 1
		d[b] = minimum
	elif a == 'R':
		maximum += 1
		d[b] = maximum
	elif a == '?':
		print(min(d[b] - minimum, maximum - d[b]))


l = 0
r = 0
n = int(200000.0 + 4)
idx = [0] * n
res = []
for i in range(int(input())):
	(op, x) = input().split()
	x = int(x)
	if i == 0:
		idx[x] = l
		continue
	if op == 'L':
		l -= 1
		idx[x] = l
	elif op == 'R':
		r += 1
		idx[x] = r
	else:
		res.append(min(idx[x] - l, r - idx[x]))
print(*res, sep='\n')


t = int(input())
a = list(range(t))
for t_itr in range(t):
	a[t_itr] = input().split()
l = 0
r = 0
pos = {}
for i in range(t):
	if i == 0:
		pos[int(a[0][1])] = 0
		l -= 1
		r += 1
	elif a[i][0] == 'L':
		pos[int(a[i][1])] = l
		l -= 1
	elif a[i][0] == 'R':
		pos[int(a[i][1])] = r
		r += 1
	else:
		ans = min(abs(pos[int(a[i][1])] - l), abs(pos[int(a[i][1])] - r)) - 1
		print(ans)


res = [0] * 200001
q = int(input())
curl = 0
curr = 1
for i in range(q):
	(a, b) = map(str, input().split())
	b = int(b)
	if a == 'L':
		res[b] = curl
		curl -= 1
	elif a == 'R':
		res[b] = curr
		curr += 1
	else:
		print(min([res[b] - curl, curr - res[b]]) - 1)


from sys import stdin
all_in = stdin.readlines()
q = int(all_in[0])
zapr = list(map(lambda x: (x.split()[0], int(x.split()[1])), all_in[1:]))
(L, R) = (0, 0)
ind = dict()
ans = list()
sign = lambda x: (-1, 1)[x >= 0]
for (z, id) in zapr:
	if z == 'L':
		L -= 1
		ind[id] = L
	elif z == 'R':
		R += 1
		ind[id] = R
	elif z == '?':
		v = ind[id]
		ans.append(min(v - L - (sign(v) * sign(L) == -1), R - v - (sign(v) * sign(R) == -1)))
	else:
		exit(100500)
print('\n'.join(map(str, ans)))


import os
import sys
from collections import Counter
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import Counter

def main():
	c = Counter()
	t = int(input())
	for z in range(t):
		ali = list(map(str, input().split()))
		if z == 0:
			left = 0
			right = 0
			c[ali[1]] = 0
		elif ali[0] == 'L':
			left -= 1
			c[ali[1]] = left
		elif ali[0] == 'R':
			right += 1
			c[ali[1]] = right
		else:
			q = c[ali[1]]
			w = abs(q - left)
			e = abs(right - q)
			r = min(w, e)
			print(r)
main()


import sys
input = sys.stdin.readline
from collections import defaultdict
q = int(input())
Sd = defaultdict(str)
Ld = defaultdict(int)
Rd = defaultdict(int)
(Lc, Rc) = (0, 0)
for _ in range(q):
	(s, idx) = input().split()
	if s == 'L':
		Lc += 1
		Sd[idx] = s
		Ld[idx] = Lc
		Rd[idx] = Rc
	elif s == 'R':
		Rc += 1
		Sd[idx] = s
		Ld[idx] = Lc
		Rd[idx] = Rc
	else:
		L_add = Lc - Ld[idx]
		R_add = Rc - Rd[idx]
		if Sd[idx] == 'L':
			print(min(L_add, Ld[idx] + Rd[idx] - 1 + R_add))
		else:
			print(min(Ld[idx] + Rd[idx] - 1 + L_add, R_add))


n = int(input())
d = {}
(l, r) = (0, 0)
(t, i) = input().split()
d[i] = 0
for _ in range(n - 1):
	(t, i) = input().split()
	if t == 'L':
		l -= 1
		d[i] = l
	elif t == 'R':
		r += 1
		d[i] = r
	else:
		print(min(d[i] - l, r - d[i]))


from sys import stdin, stdout

def myfunction(mydict, current, second):
	a = mydict[second]
	if a[2] == 'R':
		return min(current[1] - a[1], current[0] + a[1] - 1)
	else:
		return min(current[0] - a[0], current[1] + a[0] - 1)
q = int(stdin.readline())
mydict = dict()
current = [0, 0, 0]
while q > 0:
	(first, second) = stdin.readline().split()
	if first == 'L':
		mydict[second] = [current[0] + 1, current[1], 'L']
		current = [current[0] + 1, current[1], 'L']
	elif first == 'R':
		mydict[second] = [current[0], current[1] + 1, 'R']
		current = [current[0], current[1] + 1, 'R']
	else:
		print(myfunction(mydict, current, second))
	q -= 1


n = int(input())
l = 0
r = 0
books = {}
z = input().split()
books[z[1]] = 0
for i in range(n - 1):
	z = input().split()
	if z[0] == 'L':
		l -= 1
		books[z[1]] = l
	elif z[0] == 'R':
		r += 1
		books[z[1]] = r
	else:
		print(min(r - books[z[1]], books[z[1]] - l))


import os
import sys
from io import BytesIO, IOBase
import math
from queue import Queue
import collections
import itertools
import bisect
import heapq
import random

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(int(n))
	return l

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)

def countcon(s, i):
	c = 0
	ch = s[i]
	for i in range(i, len(s)):
		if s[i] == ch:
			c += 1
		else:
			break
	return c

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] > arr[j] and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	return maximum

def isSubSequence(str1, str2):
	m = len(str1)
	n = len(str2)
	j = 0
	i = 0
	while j < m and i < n:
		if str1[j] == str2[i]:
			j = j + 1
		i = i + 1
	return j == m

def maxfac(n):
	root = int(n ** 0.5)
	for i in range(2, root + 1):
		if n % i == 0:
			return n // i
	return n

def p2(n):
	c = 0
	while n % 2 == 0:
		n //= 2
		c += 1
	return c

def seive(n):
	primes = [True] * (n + 1)
	primes[1] = primes[0] = False
	i = 2
	while i * i <= n:
		if primes[i] == True:
			for j in range(i * i, n + 1, i):
				primes[j] = False
		i += 1
	pr = []
	for i in range(0, n + 1):
		if primes[i]:
			pr.append(i)
	return pr

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def denofactinverse(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return pow(fac, m - 2, m)

def numofact(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return fac

def sod(n):
	s = 0
	while n > 0:
		s += n % 10
		n //= 10
	return s
q = int(input())
last = -1
pos = [-1] * 200006
inc = 0
rc = 0
le = 0
for xyz in range(0, q):
	(a, b) = input().split()
	b = int(b)
	if a == 'L':
		last = b
		inc += 1
		pos[b] = -inc
		le += 1
	elif a == 'R':
		rc += 1
		pos[b] = rc
		le += 1
	else:
		if pos[b] < 0:
			posi = pos[b] + inc
		else:
			posi = le - 1 - (rc - pos[b])
		print(min(posi, le - 1 - posi))


import sys
q = int(sys.stdin.readline().lstrip().rstrip())
(l, r) = (-1, 1)
d = {}
for _ in range(q):
	(x, val) = list(map(str, sys.stdin.readline().lstrip().rstrip().split()))
	val = int(val)
	if x == 'L':
		d[val] = l
		l -= 1
	elif x == 'R':
		d[val] = r
		r += 1
	else:
		x = d[val]
		if x < 0:
			left = abs(l) - abs(x) - 1
			right = abs(x) - 1 + r - 1
			print(min(left, right))
		else:
			left = x - 1 + abs(l) - 1
			right = r - x - 1
			print(min(left, right))


q = int(input())
l = 0
i = 0
r = 0
m = [0] * (2 * 100001)
while q:
	q -= 1
	(d, id) = map(str, input().split())
	a = int(id)
	if d == 'L':
		if i == 0:
			l = 0
			m[a] = l
			r = l
		else:
			l -= 1
			m[a] = l
	if d == 'R':
		if i == 0:
			r = 0
			m[a] = r
			l = r
		else:
			r += 1
			m[a] = r
	if d == '?':
		val = m[a]
		print(min(val - l, r - val))
	i += 1


n = int(input())
mi = 0
ma = 0
p = 10 ** 6
a = [0] * p
(x, y) = input().split()
a[int(y)] = 0
for i in range(n - 1):
	(x, y) = input().split()
	y = int(y)
	if x == 'L':
		mi -= 1
		a[y] = mi
	elif x == 'R':
		ma += 1
		a[y] = ma
	else:
		print(min(a[y] - mi, ma - a[y]))


n = int(input())
(pos, num) = input().split()
dic = {}
dic[num] = 0
left = 0
right = 0
for _ in range(n - 1):
	(pos, num) = input().split()
	if pos == 'L':
		left -= 1
		dic[num] = left
	elif pos == 'R':
		right += 1
		dic[num] = right
	else:
		print('{}'.format(min(dic[num] - left, right - dic[num])))


import sys
input = sys.stdin.readline
d = {}
n = int(input())
l = 0
r = 0
for _ in range(n):
	(a, b) = input().split()
	if _ == 0:
		d[int(b)] = 0
		l -= 1
		r += 1
		continue
	if a == 'L':
		d[int(b)] = l
		l -= 1
	elif a == 'R':
		d[int(b)] = r
		r += 1
	else:
		first = abs(d[int(b)] - l)
		second = abs(d[int(b)] - r)
		print(min(first, second) - 1)


q = int(input())
if q > 0:
	left = 0
	right = 0
	d = dict()
	[q_type, q_id] = input().split()
	d[q_id] = 0
	for i in range(q - 1):
		[q_type, q_id] = input().split()
		if q_type == 'L':
			left -= 1
			d[q_id] = left
		elif q_type == 'R':
			right += 1
			d[q_id] = right
		elif q_type == '?':
			p = d[q_id]
			print(min(p - left, right - p))


import collections
arr = [0] * 200010
query = int(input())
total = 0
l = 0
r = 0
ans = []
for test in range(query):
	(ty, idd) = [x for x in input().split()]
	idd = int(idd)
	if ty == 'L':
		l += 1
		arr[idd] = (1, l - 1)
		total += 1
	elif ty == 'R':
		r += 1
		arr[idd] = (0, r - 1)
		total += 1
	else:
		left = 0
		right = 0
		x = arr[idd]
		if x[0] == 0:
			left = l + x[1]
			right = r - x[1] - 1
		else:
			left = l - x[1] - 1
			right = r + x[1]
		ans.append(min(left, right))
for i in range(len(ans)):
	print(ans[i])


n = int(input())
r = l = 0
right_pos = {}
left_pos = {}
for _ in range(n):
	(com, id) = input().split()
	if com == 'R':
		right_pos[id] = r
		r += 1
	elif com == 'L':
		left_pos[id] = l
		l += 1
	elif id in right_pos:
		ind = right_pos[id]
		output = min(l + ind, r - ind - 1)
		print(output)
	else:
		ind = left_pos[id]
		output = min(l - ind - 1, ind + r)
		print(output)


from sys import stdin, stdout
print = stdout.write
input = stdin.readline
s = [0] * 200000
d = {}
r = 1
l = -1
a = []
t = int(input())
s[0] = input().split()[1]
d[s[0]] = 0
for x in range(t - 1):
	(q, n) = input().split()
	if q == 'L':
		s[l] = n
		d[n] = l
		l -= 1
	if q == 'R':
		s[r] = n
		d[n] = r
		r += 1
	if q == '?':
		a += [str(d[n] - l - 1) if d[n] - l < r - d[n] else str(r - d[n] - 1)]
print('\n'.join(a))


n = int(input())
(shelf, L, R) = ({}, 0, 0)
(p, d) = input().split()
shelf[d] = 0
for i in range(n - 1):
	(p, d) = input().split()
	if p == 'L':
		shelf[d] = L - 1
		L -= 1
	elif p == 'R':
		shelf[d] = R + 1
		R += 1
	else:
		a = -(L - shelf[d])
		b = R - shelf[d]
		print(min(a, b))


n = int(input())
(l, r) = (0, 1)
indexs = [0] * 200002
for i in range(n):
	[c, ind] = input().split()
	ind = int(ind)
	if c == 'L':
		indexs[ind] = l
		l -= 1
	elif c == 'R':
		indexs[ind] = r
		r += 1
	else:
		k = indexs[ind]
		print(min(k - l - 1, r - 1 - k))


q = int(input())
d = {}
l = 0
r = 1
for _ in range(q):
	(x, y) = input().split()
	if x == 'L':
		d[y] = l
		l -= 1
	elif x == 'R':
		d[y] = r
		r += 1
	else:
		print(min(d[y] - l - 1, r - d[y] - 1))


import sys
index = [0] * 200005
(l, r) = (0, 1)
query = sys.stdin.readlines()
q = int(query[0])
for _ in range(0, q):
	s = query[_ + 1].split()
	if s[0] == 'L':
		index[int(s[1])] = l
		l -= 1
	elif s[0] == 'R':
		index[int(s[1])] = r
		r += 1
	else:
		print(min(index[int(s[1])] - l - 1, r - 1 - index[int(s[1])]))


(mini, maxi) = (1, 0)
indexes = {}
ans = []
for q in range(int(input())):
	cmd = input().split()
	idx = int(cmd[1])
	if cmd[0] == 'L':
		mini -= 1
		indexes[idx] = mini
	elif cmd[0] == 'R':
		maxi += 1
		indexes[idx] = maxi
	else:
		ind = indexes[idx]
		ans.append(min(ind - mini, maxi - ind))
print(*ans, sep='\n')


from sys import *
n = int(stdin.readline())
A = {}
(i, j) = (1, 0)
for l in range(n):
	(x, y) = stdin.readline().split('\n')
	(x, k) = map(str, x.split())
	k = int(k)
	if x == '?':
		stdout.write(str(min(A[k] - i, j - A[k])) + '\n')
	elif x == 'R':
		j += 1
		A[k] = j
	else:
		i -= 1
		A[k] = i


l = 0
r = 0
d = [0 for i in range(2 * 10 ** 5 + 2)]
tt = int(input())
query = input().split()
n = int(query[1])
if query[0] == 'L':
	d[n] = l
	l -= 1
	r += 1
elif query[0] == 'R':
	d[n] = r
	r += 1
	l -= 1
for _ in range(tt - 1):
	query = input().split()
	n = int(query[1])
	if query[0] == 'L':
		d[n] = l
		l -= 1
	elif query[0] == 'R':
		d[n] = r
		r += 1
	else:
		print(min(r - d[n], d[n] - l) - 1)


import sys

class Input(object):

	def __init__(self):
		self.fh = sys.stdin

	def next_line(self):
		while True:
			line = sys.stdin.readline()
			if line == '\n':
				continue
			return line

	def next_line_ints(self):
		line = self.next_line()
		return [int(x) for x in line.split()]

	def next_line_strs(self):
		line = self.next_line()
		return line.split()

def main():
	input = Input()
	while True:
		nums = input.next_line_ints()
		if not nums:
			break
		n = nums[0]
		pos_dict = {}
		left_idx = -1
		right_idx = 0
		for _ in range(n):
			(op, id) = input.next_line_strs()
			id = int(id)
			if op == 'L':
				pos_dict[id] = left_idx
				left_idx -= 1
			elif op == 'R':
				pos_dict[id] = right_idx
				right_idx += 1
			else:
				pos = pos_dict[id]
				to_left = pos - left_idx - 1
				to_right = right_idx - 1 - pos
				print('{}'.format(min(to_left, to_right)))
main()


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
q = int(input())
books = {}
(l, r) = (0, 0)
for query in range(q):
	inp = input().split()
	pl = inp[0]
	id = int(inp[1])
	if pl == b'R':
		r += 1
		books[id] = [r, 'r']
	elif pl == b'L':
		l += 1
		books[id] = [l, 'l']
	else:
		b = books[id]
		if b[1] == 'r':
			print(min(r - b[0], l + b[0] - 1))
		elif b[1] == 'l':
			print(min(l - b[0], r + b[0] - 1))


def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()
for t in range(1):
	n = int(input())
	arr = dict()
	l = 0
	r = 1
	for i in range(n):
		(x, y) = input().split()
		if x == 'L':
			arr[y] = l
			l -= 1
		elif x == 'R':
			arr[y] = r
			r += 1
		else:
			pos = arr[y]
			print(min(pos - l - 1, r - pos - 1))


t = int(input())
s = [0] * 10 ** 6
q = 0
i = 0
while i < t:
	y = input().split(' ')
	if y[0] == 'R':
		s[int(y[1])] = i - q
	elif y[0] == 'L':
		q += 1
		s[int(y[1])] = -q
	else:
		print(min(s[int(y[1])] + q, i - 1 - q - s[int(y[1])]))
		i -= 1
		t -= 1
	i += 1


n = int(input())
(s, e) = (0, 0)
c = True
w = dict()
for _ in range(n):
	(q, d) = input().split()
	if q == 'R':
		if c:
			s += 1
			c = False
		e += 1
		w[d] = e
	elif q == 'L':
		if c:
			e -= 1
			c = False
		s -= 1
		w[d] = s
	else:
		i = w[d]
		if i > e:
			i -= n
		print(min(e - i, i - s))


q = int(input())
(d, i, j, f) = (dict(), 0, 0, True)
while q > 0:
	(p, k) = input().split()
	if f:
		d[k] = d.get(k, 0)
		f = not f
	elif p == 'L':
		i -= 1
		d[k] = d.get(k, i)
	elif p == 'R':
		j += 1
		d[k] = d.get(k, j)
	else:
		print(min(abs(i - d.get(k)), abs(j - d.get(k))))
	q -= 1


n = int(input())
index = {}
left = 0
right = 1
for _ in range(n):
	(l_or_r, idx) = input().split()
	if l_or_r == 'L':
		index[idx] = left
		left -= 1
	elif l_or_r == 'R':
		index[idx] = right
		right += 1
	else:
		print(min(index[idx] - (left + 1), right - 1 - index[idx]))


import sys

def solution(q):
	placed = False
	lind = 0
	rind = 0
	book_map = {}
	for i in range(q):
		(op, book_ind) = [val for val in sys.stdin.readline().split()]
		book_ind = int(book_ind)
		if op == 'R':
			book_map[book_ind] = rind
			rind += 1
			if not placed:
				placed = True
				lind -= 1
		elif op == 'L':
			book_map[book_ind] = lind
			lind -= 1
			if not placed:
				placed = True
				rind += 1
		elif op == '?':
			ldist = book_map[book_ind] - lind
			rdist = rind - book_map[book_ind]
			print(min(ldist, rdist) - 1)

def __starting_point():
	q = [int(val) for val in sys.stdin.readline().split()][0]
	solution(q)
__starting_point()


q = int(input())
dc = dict()
l = 0
r = 0
(z, n) = input().split()
n = int(n)
dc[n] = l
for i in range(q - 1):
	(z, n) = input().split()
	n = int(n)
	if z == 'L':
		l -= 1
		dc[n] = l
	elif z == 'R':
		r += 1
		dc[n] = r
	else:
		print(min(dc[n] - l, r - dc[n]))


q = int(input())
ar = [0] * 300000
(last_l, last_r) = (1, 0)
for i in range(q):
	(c, x) = input().split()
	if c == 'L':
		last_l = last_l - 1
		ar[int(x)] = last_l
	elif c == 'R':
		last_r = last_r + 1
		ar[int(x)] = last_r
	else:
		print(min(last_r - ar[int(x)], ar[int(x)] - last_l))


n = int(input())
book_coor = dict()
lev_coor = 0
prav_coor = -1
for _ in range(n):
	(q, id) = input().split()
	if q == 'L':
		lev_coor -= 1
		book_coor[id] = lev_coor
	elif q == 'R':
		prav_coor += 1
		book_coor[id] = prav_coor
	else:
		print(min(book_coor[id] - lev_coor, prav_coor - book_coor[id]))


n = int(input())
a = {}
(l, r) = (1, 0)
for i in range(n):
	(c, x) = input().split()
	if c == 'L':
		l -= 1
		a[x] = l
	elif c == 'R':
		r += 1
		a[x] = r
	else:
		print(min(a[x] - l, r - a[x]))


q = int(input())
bign = int(200000.0 + 33)
L = [0 for i in range(bign)]
R = [0 for i in range(bign)]
nowr = 0
nowl = 0
for i in range(q):
	myin = input().strip().split()
	x = int(myin[1])
	if myin[0][0] == '?':
		print(min(nowr - R[x], nowl - L[x]))
		continue
	if myin[0][0] == 'R':
		nowr = nowr + 1
		L[x] = -nowr + 1
		R[x] = nowr
	elif myin[0][0] == 'L':
		nowl = nowl + 1
		L[x] = nowl
		R[x] = -nowl + 1


l = 1
r = 0
L = [0] * 10 ** 6
for _ in range(int(input())):
	(a, b) = input().split()
	if a == 'L':
		l -= 1
		L[int(b)] = l
	elif a == 'R':
		r += 1
		L[int(b)] = r
	else:
		print(min(L[int(b)] - l, r - L[int(b)]))


def main(input):
	sp = [0] * 200021
	(L, R) = (1, 0)
	for i in range(int(input())):
		(s, ids) = input().split()
		ids = int(ids)
		if s == 'L':
			L -= 1
			sp[ids] = L
		elif s == 'R':
			R += 1
			sp[ids] = R
		else:
			print(min(sp[ids] - L, R - sp[ids]))
main(input)


import sys

def rint():
	return map(int, sys.stdin.readline().split())
q = int(input())
order = [0] * (2 * 10 ** 5 + 1)
lm_order = 0
rm_order = 0
not_init = 1
for i in range(q):
	(cmd, id) = sys.stdin.readline().split()
	id = int(id)
	if cmd == 'L':
		order[id] = lm_order - 1
		lm_order = lm_order - 1
		if not_init:
			rm_order = lm_order
			not_init = 0
	elif cmd == 'R':
		order[id] = rm_order + 1
		rm_order = rm_order + 1
		if not_init:
			lm_order = rm_order
			not_init = 0
	else:
		print(min(order[id] - lm_order, rm_order - order[id]))


from sys import *
(x, y) = stdin.readline().split('\n')
n = int(x)
A = {}
(l, r) = (1, 0)
while n:
	x = stdin.readline()
	if x == '\n':
		continue
	n -= 1
	(o, y) = x.split('\n')
	(o, i) = map(str, o.split())
	if o == 'L':
		l -= 1
		A[i] = l
	elif o == 'R':
		r += 1
		A[i] = r
	else:
		stdout.write(str(int(min(A[i] - l, r - A[i]))) + '\n')


def solve(requests):
	q = dict()
	(l, r) = (0, 1)
	res = []
	for request in requests:
		if request[0] == 'R':
			q[request[1]] = r
			r += 1
		elif request[0] == 'L':
			q[request[1]] = l
			l -= 1
		else:
			s = min(r - q[request[1]] - 1, q[request[1]] - l - 1)
			res.append(s)
	return res
tests = int(input())
requests = []
for i in range(tests):
	q = input().split()
	q[1] = int(q[1])
	requests.append(q)
res = solve(requests)
print('\n'.join([str(x) for x in res]))


from collections import *
from math import *
from itertools import *

def I():
	return map(int, input().strip().split())
arr = defaultdict(int)
mp = defaultdict(str)
pivot = 0
inside = 0
prev1 = 0
prev2 = 0
(l, r) = (-1, -1)
for Q in range(int(input())):
	(q, n) = input().split()
	n = int(n)
	if l == -1 and r == -1:
		inside += 1
		(l, r) = (n, n)
		arr[n] = prev1
	elif q == 'R':
		r = n
		inside += 1
		arr[n] = prev2 + 1
		prev2 += 1
	elif q == 'L':
		l = n
		inside += 1
		arr[n] = prev1 - 1
		prev1 -= 1
	else:
		print(min(arr[r] - arr[n], arr[n] - arr[l]))


MAX_LEN = 200000
n = int(input())
d = {}
(_, book_id) = input().split()
book_id = int(book_id)
d[book_id] = 0
left = 0
right = 0
for _ in range(n - 1):
	(command, book_id) = input().split()
	book_id = int(book_id)
	if command == 'L':
		left = (left - 1) % MAX_LEN
		d[book_id] = left
	elif command == 'R':
		right = (right + 1) % MAX_LEN
		d[book_id] = right
	elif command == '?':
		idx = d[book_id]
		print(min((right - idx) % MAX_LEN, (idx - left) % MAX_LEN))


n = int(input())
indr = 0
indl = 0
d = {}
for i in range(n):
	(t, id) = input().split()
	id = int(id)
	if i == 0:
		d[id] = 0
		continue
	if t == 'L':
		indl -= 1
		d[id] = indl
	elif t == 'R':
		indr += 1
		d[id] = indr
	else:
		k1 = abs(indr - d[id])
		k2 = abs(indl - d[id])
		print(min(k1, k2))


q = int(input())
bookList = dict()
rc = 0
lc = 0
RL = []
LL = []
for qi in range(q):
	(Type, ID) = input().split(' ')
	ID = int(ID)
	if Type == 'L':
		if qi == 0:
			RL.append(ID)
			bookList[ID] = ['R', rc]
			rc += 1
		else:
			LL.append(ID)
			bookList[ID] = ['L', lc]
			lc += 1
	elif Type == 'R':
		RL.append(ID)
		bookList[ID] = ['R', rc]
		rc += 1
	else:
		point = bookList[ID]
		if point[0] == 'R':
			idx = point[1] + lc
		else:
			idx = lc - point[1] - 1
		left = idx
		right = lc + rc - idx - 1
		print(min(left, right))


(l, r) = (1, 0)
a = [0] * 200010
for _ in range(int(input())):
	(s, t) = input().split()
	t = int(t)
	if s == 'L':
		l -= 1
		a[t] = l
	elif s == 'R':
		r += 1
		a[t] = r
	else:
		print(min(a[t] - l, r - a[t]))


n = int(input())
curl = -1
curr = 1
s = input().split()
books = dict()
books[s[1]] = 0
out = ''
for i in range(1, n):
	s = input().split()
	if s[0] == 'L':
		books[s[1]] = curl
		curl -= 1
	elif s[0] == 'R':
		books[s[1]] = curr
		curr += 1
	else:
		out += str(min(curr - books[s[1]], books[s[1]] - curl) - 1) + '\n'
print(out)


a = int(input())
v = 0
s = 1
d = dict()
for i in range(a):
	(b, r) = input().split()
	if b == 'R':
		v = v + 1
		d[r] = v
	elif b == 'L':
		s = s - 1
		d[r] = s
	else:
		print(min(v - d[r], d[r] - s))


q = int(input())
dict_position = {}
max_L = None
max_R = None
for _ in range(q):
	a = input().split()
	(action, book_id) = (a[0], int(a[1]))
	if action == 'R':
		if max_R is None:
			max_L = 0
			max_R = 0
		else:
			max_R += 1
		dict_position[book_id] = max_R
	elif action == 'L':
		if max_L is None:
			max_L = 0
			max_R = 0
		else:
			max_L -= 1
		dict_position[book_id] = max_L
	elif action == '?':
		print(min(abs(dict_position[book_id] - max_L), abs(dict_position[book_id] - max_R)))


(lewo, prawo) = (1, 0)
a = {}
for _ in [0] * int(input()):
	(c, b) = input().split()
	if c == 'L':
		lewo -= 1
		a[b] = lewo
	elif c == 'R':
		prawo += 1
		a[b] = prawo
	else:
		print(min(a[b] - lewo, prawo - a[b]))


q = int(input())
mem = dict()
(_, n) = input().split()
n = int(n)
left = 0
right = 0
mem[n] = 0
for _ in range(q - 1):
	(s, n) = input().split()
	n = int(n)
	if s == 'L':
		left -= 1
		mem[n] = left
	elif s == 'R':
		right += 1
		mem[n] = right
	else:
		print(min(mem[n] - left, right - mem[n]))


t = int(input())
l = []
n = 0
pos = {}
cur = 0
cul = 0
f = 1
while t:
	t -= 1
	(ch, a) = [x for x in input().split()]
	a = int(a)
	if f == 1:
		f = 0
		pos[a] = cur
		cur += 1
		cul -= 1
	elif ch == 'L':
		pos[a] = cul
		cul -= 1
	elif ch == 'R':
		pos[a] = cur
		cur += 1
	else:
		print(min(abs(cul - pos[a]), abs(cur - pos[a])) - 1)


from sys import stdin, stdout

def main():
	q = int(stdin.readline())
	query = {}
	l = r = 200005
	while q:
		q -= 1
		(char, book) = stdin.readline().split()
		if char == 'L':
			if l == r:
				r += 1
			query.setdefault(book, l)
			l -= 1
		elif char == 'R':
			if l == r:
				l -= 1
			query.setdefault(book, r)
			r += 1
		else:
			stdout.write('%d\n' % min(query[book] - (l + 1), r - 1 - query[book]))
main()


q = int(input())
numL = 0
numR = 0
leftId = {}
rightId = {}
for i in range(q):
	(pos, id) = input().split()
	if pos == 'L':
		numL += 1
		leftId[id] = numL
	elif pos == 'R':
		numR += 1
		rightId[id] = numR
	elif id in leftId.keys():
		fromLeft = numL - leftId[id]
		fromRight = numR + leftId[id] - 1
		print(min(fromLeft, fromRight))
	else:
		fromLeft = numL + rightId[id] - 1
		fromRight = numR - rightId[id]
		print(min(fromLeft, fromRight))


q = int(input())
(l, r, i, j) = (dict(), dict(), -1, -1)
while q > 0:
	(p, k) = input().split()
	if p == 'L':
		i += 1
		l[k] = l.get(k, i)
	elif p == 'R':
		j += 1
		r[k] = r.get(k, j)
	elif l.get(k, -1) >= 0:
		if i - l.get(k) <= j + l.get(k) + 1:
			print(i - l.get(k))
		else:
			print(j + l.get(k) + 1)
	elif j - r.get(k) <= i + r.get(k) + 1:
		print(j - r.get(k))
	else:
		print(i + r.get(k) + 1)
	q -= 1


from collections import deque
import collections, itertools
t = int(input())
arr = deque()
count = 0
d = {}
l = 0
r = 0
while t > 0:
	t -= 1
	(n, m) = map(str, input().split())
	m = int(m)
	if n == 'L':
		d[m] = l
		l -= 1
		if l == -1 and r == 0:
			r = 1
	elif n == 'R':
		d[m] = r
		r += 1
		if l == 0 and r == 1:
			l = -1
	else:
		f = d[m]
		print(min(f - l - 1, r - f - 1))


t = int(input())
d = {}
l = 0
r = 0
while t > 0:
	t -= 1
	(n, m) = map(str, input().split())
	m = int(m)
	if n == 'L':
		d[m] = l
		l -= 1
		if l == -1 and r == 0:
			r = 1
	elif n == 'R':
		d[m] = r
		r += 1
		if l == 0 and r == 1:
			l = -1
	else:
		f = d[m]
		print(min(f - l - 1, r - f - 1))


a = [0] * 400000
q = int(input())
l = 0
r = 1
for i in range(q):
	(op, ident) = input().split()
	ident = int(ident)
	if op == 'L':
		a[ident] = l
		l -= 1
	elif op == 'R':
		a[ident] = r
		r += 1
	else:
		print(min(a[ident] - l, r - a[ident]) - 1)


from sys import stdin, stdout

def main():
	q = int(input())
	query = {}
	l = r = 200005
	while q:
		q -= 1
		(char, book) = input().split()
		if char == 'L':
			if l == r:
				r += 1
			query.setdefault(book, l)
			l -= 1
		elif char == 'R':
			if l == r:
				l -= 1
			query.setdefault(book, r)
			r += 1
		else:
			print(min(query[book] - (l + 1), r - 1 - query[book]))
main()


n = int(input())
n -= 1
R = 0
L = 0
m = {input().split()[1]: 0}
while n:
	(a, b) = input().split()
	if a == 'L':
		L -= 1
		m[b] = L
	elif a == 'R':
		R += 1
		m[b] = R
	else:
		print(min(R - m[b], m[b] - L))
	n -= 1