-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path18258.py
More file actions
64 lines (56 loc) ยท 2.84 KB
/
18258.py
File metadata and controls
64 lines (56 loc) ยท 2.84 KB
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
from collections import deque
from sys import stdin
dq = deque()
N = int(stdin.readline())
for _ in range(N):
arr = stdin.readline().split()
method = arr[0]
if method == "push":
dq.append(arr[1])
if method == "front":
if len(dq) == 0:
print(-1)
else:
print(dq[0])
if method == "back":
if len(dq) == 0:
print(-1)
else:
print(dq[-1])
if method == "size":
print(len(dq))
if method == "empty":
if len(dq) == 0:
print(1)
else:
print(0)
if method == "pop":
if len(dq) == 0:
print(-1)
else:
print(dq.popleft())
# ๋ฐฑ์ค 18258 ํ 2: ์ง์ ๊ตฌํ vs deque, ๊ทธ๋ฆฌ๊ณ ์ ํ ์ด์
# ์ด ๊ธ์์๋ ํ๋ฅผ ์ง์ ๊ตฌํํ ๋ฒ์ ๊ณผ collections.deque๋ฅผ ํ์ฉํ ๋ฒ์ ์ ๋๋ํ ์๊ฐํ๊ณ , ์ ์ค์ ์์๋ deque๋ฅผ ์ฐ๋์ง ํต์ฌ ์ด์ ๋ฅผ ์ ๋ฆฌํฉ๋๋ค.
# ์ง์ ํ ๊ตฌํ (๋ฆฌ์คํธ + head ์ธ๋ฑ์ค, O(1) pop)
# ๋ฆฌ์คํธ์ ์์์ ์์๋ฅผ ๊บผ๋ด๋ฉด O(n)์ด๋ฏ๋ก, ์์์ ์ค์ ๋ก ์ญ์ ํ์ง ์๊ณ head ํฌ์ธํฐ๋ง ์ฆ๊ฐ์ํค๋ ๋ฐฉ์์ผ๋ก O(1) pop์ ๋ฌ์ฑํฉ๋๋ค.
# Apply to 1157.py
# )
# ์๊ฐ๋ณต์ก๋: push, pop, front, back, empty, size ๋ชจ๋ O(1)
# ์ฃผ์: head๊ฐ ์ปค์ง๋ฉฐ ๋ฆฌ์คํธ ์๋ถ๋ถ์ด โ๋
ผ๋ฆฌ์ ์ผ๋ก๋งโ ๋น์์ง(๋ฉ๋ชจ๋ฆฌ ํ์ ์์). ๋ฌธ์ ํฌ๊ธฐ ๋ด์์๋ ์์ .
# deque ๋ฒ์ (๊ฐ๊ฒฐํ๊ณ ์์ ํ ํ์ค ํด๋ฒ)
# )
# append, popleft๊ฐ ๋ชจ๋ O(1) ๋ณด์ฅ.
# ์ฝ๋๊ฐ ๊ฐ๊ฒฐํ๊ณ , ์ธ๋ฑ์ค ๊ด๋ฆฌ๊ฐ ํ์ ์์ด ์ค์ ์ฌ์ง๊ฐ ์ ์.
# ์ deque๋ฅผ ์ฐ๋๊ฐ?
# O(1) ์๋ ์ฐ์ฐ ๋ณด์ฅ: append, appendleft, pop, popleft ๋ชจ๋ ํ๊ท O(1). ๋ฆฌ์คํธ์ pop(0)์ O(n)์ด๋ผ ๋๋ ์ฐ์ฐ์์ ์๊ฐ์ด๊ณผ ์ํ.
# ๊ตฌํ ์์ ์ฑ: ์ธ๋ฑ์ค ํฌ์ธํฐ ๊ด๋ฆฌ ์์ด๋ ์ฌ๋ฐ๋ฅธ ๋์. ์ค์ ๊ฐ๋ฅ์ฑยท๋๋ฒ๊น
๋น์ฉ์ด ๋ฎ์.
# C๋ก ์ต์ ํ: CPython์์ deque๋ C๋ก ๋ง๋ค์ด์ ธ ์ค์ ๋ฐํ์์ด ๋น ๋ฅด๊ณ ์ผ๊ด์ .
# ๊ฐ๋
์ฑ: ์๋๊ฐ ๋ช
ํํด ์ฝ๋ ๋ฆฌ๋ทฐยทํ์
์ ์ ๋ฆฌ.
# ์ง์ ๊ตฌํ(head ์ธ๋ฑ์ค) ๋ฐฉ์๋ ์ถฉ๋ถํ ๋น ๋ฅด์ง๋ง, ์ค์ (ํนํ ๋ฐฑ์ค ๋์ฉ๋ ์
์ถ๋ ฅ)์์๋ deque๊ฐ ๋ ๊ฐ๋จํ๊ณ ์์ ํ โํ์ค ํด๋ฒโ์
๋๋ค. ๋จ, ์ต์ ์
์ถ๋ ฅ์ ์ํด sys.stdin.readline๊ณผ ์ถ๋ ฅ ๋ฒํผ๋ง(์: '\n'.join(...))์ ํจ๊ป ์ฐ๋ฉด ์ถ๊ฐ๋ก ์๊ฐ์ ์ ์ฝํ ์ ์์ต๋๋ค.
# ๋ณต์ก๋ ํ๋์ ๋น๊ต
# ์ง์ ๊ตฌํ(head ์ธ๋ฑ์ค): ๋ชจ๋ ์ฐ์ฐ O(1), ๋ฉ๋ชจ๋ฆฌ ํ์๋ ์ ๋จ(๋ฌธ์ ์ค์ผ์ผ ๋ด ๋ฌด๊ด).
# deque: ๋ชจ๋ ์ฐ์ฐ O(1), ๊ตฌํ ๊ฐ๊ฒฐ/์์ , ์ค์ ์์ ๊ถ์ฅ.
# ๊ฐ๋จ ์์ฝ
# ์ง์ ๊ตฌํ: ๋ฆฌ์คํธ + head ์ธ๋ฑ์ค ์ฆ๊ฐ๋ก O(1) pop ํ๋ณด.
# deque: ๋ ๊ฐ๊ฒฐํ๊ณ ์ค์ ์ ์ผ๋ฉฐ C ์ต์ ํ๋ก ๋น ๋ฆ.
# ์
์ถ๋ ฅ ์ต์ ํ: sys.stdin.readline, ์ถ๋ ฅ ๋ชจ์์ ํ ๋ฒ์ ์ฐ๊ธฐ ์ถ์ฒ.