'''
并查集维护每个节点到根的距离,集合a并到集合b时候,a中所有节点到根的距离加上
b子集的大小,直接在a自己根节点的距离上加上b子集大小即可
'''
import sys
class MergeSetExt:
def __init__(self, max_key_val = 0, trans_key_func=None):
if trans_key_func is not None and max_key_val > 0:
# 如果能够提供转换key的回调,并查集内部用线性表存储
self.trans_key_callback = trans_key_func
self.m = [-1 for _ in range(max_key_val+1)]
self.__root2cluster_size = [0 for _ in range(max_key_val+1)]
self.__root_dis = [0 for _ in range(max_key_val+1)] # 节点到根的距离
else:
# 如果不能提供转换key的回调,并查集内部用hash表存储
self.trans_key_callback = None
self.m = {}
self.__root2cluster_size = {}
self.__root_dis = {}
self.__root_cnt = 0
def getRoot(self, node):
buf = []
root = self.trans_key_callback(node) if self.trans_key_callback else node
while self.m[root] != root:
buf.append(root)
root = self.m[root]
last_val = 0
for key in reversed(buf):
self.m[key] = root
self.__root_dis[key] += last_val
last_val = self.__root_dis[key]
return root
def get_dis(self, node):
node = self.trans_key_callback(node) if self.trans_key_callback else node
return self.__root_dis[node]
def merge(self, a, b):
orig_a, orig_b = a, b
if self.trans_key_callback:
a, b = self.trans_key_callback(a), self.trans_key_callback(b)
for node in [a, b]:
if (self.trans_key_callback is None and node not in self.m) or (self.trans_key_callback is not None and self.m[node] == -1):
self.m[node] = node
self.__root2cluster_size[node] = 1
self.__root_cnt += 1
self.__root_dis[node] = 0
root1 = self.getRoot(orig_a)
root2 = self.getRoot(orig_b)
dis2 = self.__root2cluster_size[root2]
if root1 != root2:
self.__root_dis[root1] += dis2
self.m[root1] = root2
self.__root2cluster_size[root2] += self.__root2cluster_size[root1]
if self.trans_key_callback:
self.__root2cluster_size[root1] = 0
else:
self.__root2cluster_size.pop(root1)
self.__root_cnt -= 1
# 根据根节点的数值获取其所在的簇的大小
def getClusterSize(self, root):
return self.__root2cluster_size[root]
def isInSameSet(self, a, b):
if a == b:
return True
orig_a, orig_b = a, b
if self.trans_key_callback:
a, b = self.trans_key_callback(a), self.trans_key_callback(b)
for node in [a, b]:
if self.m[node] == -1:
return False
else:
for node in [orig_a, orig_b]:
if node not in self.m:
return False
return self.getRoot(orig_a) == self.getRoot(orig_b)
def getRootNum(self):
return self.__root_cnt
def getClusters(self):
rec = {}
if self.trans_key_callback is None:
for node in self.m:
root = self.getRoot(node)
if root not in rec:
rec[root] = []
rec[root].append(node)
else:
for node in range(len(self.m)):
if self.m[node] == -1:
continue
root = self.getRoot(node)
if root not in rec:
rec[root] = []
rec[root].append(node)
return [nodes for nodes in rec.values()]
merge_set = MergeSetExt()
t = int(input())
for _ in range(t):
s = sys.stdin.readline()
ch, a, b = s.split()
a, b = int(a), int(b)
if ch == 'M':
merge_set.merge(a, b)
else:
if a == b:
print(0)
else:
if merge_set.isInSameSet(a, b):
print(abs(merge_set.get_dis(a) - merge_set.get_dis(b)) - 1)
else:
print(-1)