def update_links(links, value):
for h, w in links:
table[h][w][0] = value
def init_links(links):
for h, w in links:
table[h][w] = ['EMPTY', {(h, w)}]
def update(command):
if len(command) == 3:
h, w, value = command
h, w = int(h) - 1, int(w) - 1
_, links = table[h][w]
update_links(links, value)
else:
value1, value2 = command
for h in range(n) :
for w in range(n) :
value, links = table[h][w]
if value == value1 : table[h][w][0] = value2
def merge(command):
h1, w1, h2, w2 = map(int, command)
if h1 == h2 and w1 == w2 : return
h1, w1, h2, w2 = h1-1, w1-1, h2-1, w2-1
value1, links1 = table[h1][w1]
value2, links2 = table[h2][w2]
links = links1.union(links2)
value = value1 if value1 != "EMPTY" else value2
update_links(links, value)
for h, w in links :
table[h][w][1] = links
def unmerge(command):
h, w = map(int, command)
h, w = h - 1, w - 1
value, links = table[h][w]
init_links(links)
table[h][w][0] = value
def print_(command):
h, w = map(int, command)
h, w = h - 1, w - 1
value, _ = table[h][w]
return value
# 테이블 및 value_storage 초기화
n = 50
table = [[["EMPTY", {(h, w)}] for w in range(n)] for h in range(n)]
def solution(commands):
answer = []
for command in commands:
command_type, values = command.split(' ', 1)[0], command.split(' ')[1:]
if command_type == 'UPDATE':
update(values)
elif command_type == 'MERGE':
merge(values)
elif command_type == 'UNMERGE':
unmerge(values)
elif command_type == 'PRINT':
answer.append(print_(values))
return answer