λ°±μ€ 10828 : μ€ν (+νμ΄μ¬μμ switch-case ꡬν)
Algorithms & Data structures
π μ€ν°λ μ 보
graceful-canary-e9f.notion.site
π λ¬Έμ μμ½
μ λ ₯ 컀맨λμ λ°λΌ μ€νμ push, pop λ±μ ꡬννλ λ¬Έμ
- μ λ ₯
첫째 μ€ : 컀맨λ μ€ν νμ (1 β€ N β€ 10,000)
nλ²: 컀맨λ
- μΆλ ₯
λΉ μ€νμ λνμ¬ μ»€λ§¨λκ° λͺ¨λ μ€νλ νμ μ€ν
- μμ
size - μ€ν κΈΈμ΄ μΆλ ₯ empty - λΉμ΄μλμ§ μ¬λΆ μ²΄ν¬ (yes-1, no-0)
pop - μ€ν μ΅μλ¨ μ κ±° top - μ€ν μ΅μλ¨ μΆλ ₯ push 123 - μ€νμ μ«μ 123 μκΈ°
π λ¬Έμ νμ΄
- μ¬μ©ν μλ£κ΅¬μ‘° λ° μκ³ λ¦¬μ¦
- μ€ν
- μμ€ μ½λ λ° λ¬Έμ νμ΄
λ°©λ² 1μ λ¨μ if-elseλ¬Έμ νμ©, λ°©λ² 2λ switch-caseλ¬Έμ νμ΄μ¬ λμ λλ¦¬λ‘ μ μ¬νκ² κ΅¬νν΄λ³΄μμ΅λλ€.
- 4λ°° λΉ λ₯Έ κ²μ μκ°
μλͺ¨λ μκ°μ 보면 μλκ° 4λ°° μ΄μ μ°¨μ΄κ° λλ€λ κ±Έ μ μ μλλ°μ, κ·Έ μ΄μ λ if-elseλ¬Έμ μνλ μ‘°κ±΄μ΄ λμ¬ λκΉμ§ μμ°¨μ μΌλ‘ βλͺ¨λ β κ²½μ°λ₯Ό λΉκ΅νμ§λ§, λμ λλ¦¬λ‘ κ΅¬νλ switch-case ꡬ문μ Hash tableλ‘ κ΅¬νλμ΄ μ 체 λ°μ΄ν°μ κ²μμ΄ νμμκΈ°μ μνλ κ³³μΌλ‘ νλ²μ μ΄λμ΄ κ°λ₯ν©λλ€.
- μ₯μ κ³Ό λ¨μ μ μ‘°ν©
νμ΄μ¬μλ switch - case λ¬Έμ΄ μμ΄μ λΉμ·νκ² λμ λλ¦¬λ‘ κ΅¬νν΄λ³΄μμ΅λλ€. μ½λλ ν¨μ¬ κΈΈμ΄μ‘μ§λ§ μ€νλ¬Έκ³Ό μ μΈλΆμ΄ νμ€νκ² λΆλ¦¬λμ΄ κ°λ μ±μ΄ μ’μμ§λ κ² κ°μ΅λλ€.
νμ§λ§ μλ λ°©λ²1,2 λͺ¨λ μ½λ μ λ΅μ λ°νν©λλ€. μ 체 νλ‘κ·Έλ¨ μ±λ₯μ ν¬λ¦¬ν°μ»¬νκ² μν₯μ λ―ΈμΉλμ§ κ³ λ―Όν΄λ³΄κ³ μ ννλ λ¨κ³κ° νμν κ² κ°μ΅λλ€.
# λ°©λ² 1.
# λ©λͺ¨λ¦¬: 116608KB
# μκ°: 164MS
import sys
input = sys.stdin.readline
N = int(input())
res = []
for _ in range(N):
cmd = input().split()
action, num = None, None
if len(cmd) == 1:
action = cmd[-1]
else:
action, num = cmd
if action == 'push':
res.append(num)
elif action == 'pop':
if res:
print(res.pop())
else:
print(-1)
elif action == 'size':
print(len(res))
elif action == 'empty':
if res:
print(0)
else:
print(1)
elif action == 'top':
if res:
print(res[-1])
else:
print(-1)
# λ°©λ² 2.
# λ©λͺ¨λ¦¬: 30616KB
# μκ°: 44ms
import sys
input = sys.stdin.readline
def push(res, num):
res.append(num)
return res
def pop(res):
if res:
print(res.pop())
else:
print(-1)
return res
def size(res):
print(len(res))
return res
def empty(res):
if res:
print(0)
else:
print(1)
return res
def top(res):
if res:
print(res[-1])
else:
print(-1)
return res
cmd_dict = {
"push": push,
"pop": pop,
"size": size,
"empty": empty,
"top": top
}
N = int(input())
res = []
for _ in range(N):
cmd = input().rstrip().split()
if len(cmd) == 1:
action = cmd[0]
res = cmd_dict[action](res)
else:
action, num = cmd
res = cmd_dict[action](res, num)
