https://programmers.co.kr/learn/courses/30/lessons/81303
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from dataclasses import dataclass
class Table:
@dataclass
class Node:
id: int
name = None
act = True
b = None
f = None
def __init__(self, n, k): # O(n)
self.cursor = k
self.nodes = [self.Node(i_node) for i_node in range(n)]
for i_node in range(n):
self.nodes[i_node].b = None if i_node == 0 else self.nodes[i_node-1]
self.nodes[i_node].f = None if i_node == (n-1) else self.nodes[i_node+1]
# for i_node, name in enumerate(['0 무지', '1 콘', '2 어피치', '3 제이지', '4 프로도', '5 네오', '6 튜브', '7 라이언']):
# self.nodes[i_node].name = name
self.delete_memory = []
def disconnect(self, v): # O(1)
v.act = False
if v.b is not None: v.b.f = v.f
if v.f is not None: v.f.b = v.b
def connect(self, v): # O(1)
v.act = True
if v.b is not None: v.b.f = v
if v.f is not None: v.f.b = v
def handle(self, action, val=None):
v = self.nodes[self.cursor]
# eval(f"self.{action}")(v, val) # 느리기 때문에 coding test에선 금물!
if action == 'U': self.U(v, val)
elif action == 'D': self.D(v, val)
elif action == 'C': self.C(v)
elif action == 'Z': self.Z(v)
def U(self, v, val): # O(n)
for _ in range(int(val)):
v = v.b
if v is None:
return False
self.cursor = v.id
def D(self, v, val): # O(n)
for _ in range(int(val)):
v = v.f
if v is None:
return False
self.cursor = v.id
def C(self, v, val=None): # O(1)
self.disconnect(v)
self.delete_memory.append(v)
if self.D(v, 1) is False:
self.U(v, 1)
def Z(self, v, val=None): # O(1)
v = self.delete_memory.pop()
self.connect(v)
def print(self):
print("-----------------------------------")
for v in self.nodes:
print(v.name, v.act, end='\t')
if v.id == self.cursor:
print("<-", end='')
print()
def answer(self):
return ''.join(['O' if v.act else 'X' for v in self.nodes])
def solution(n, k, cmd):
table = Table(n, k)
# table.print()
for cmd_sample in cmd: # O(|cmd|)
table.handle(*cmd_sample.split())
# table.print()
# print(cmd_sample)
return table.answer()
Complexity
$O(n \times |\text{cmd}|)$
Reminder
eval()
은 사용하지 말자. 너무 느리다.
PREVIOUSEtc