3986. 좋은 단어(스택)
•
짝지어 주지만, 겹쳐서는 안되는 문제
•
이전 값과 같은지를 확인하면서,
◦
다를 경우 그냥 더해주고
◦
같을 경우 이전값을 삭제해주면서 함께 소거되어가는 형식
n = int(stdin.readline())
count = 0
for _ in range(n):
s = list(map(str, stdin.readline().strip()))
stack = [0]
for i in s:
if stack[-1] == i: # 바로 이전에 있는 값과 같다면
stack.pop() # 이전에 있던 값을 pop(없애기)
else:
stack.append(i) # 이전에 있는 값과 다르다면 값 입력
if len(stack) == 1: # stack에 0만 남아있다면
count += 1
print(count)
Python
복사
10845. 큐
from sys import stdin
from collections import deque
queue = deque([])
N = int(stdin.readline())
def _ in range(N):
a = stdin.readline().split()
if a[0] == 'push':
queue.append(int(a[1]))
elif a[0] == 'pop':
if queue: print(queue.popleft())
else: print(-1)
elif a[0] == 'size':
print(len(queue))
elif a[0] == 'empty':
if queue: print(0)
else: print(1)
elif a[0] == 'front':
if queue: print(queue[0])
else: print(-1)
elif a[0] == 'back':
if queue: print(queue[-1])
else: print(-1)
Python
복사
Python
복사
9012. 괄호
Python
복사
2164. 카드2
from sys import stdin
from collections import deque
N = int(stdin.readline())
q = deque()
for i in range(N):
q.append(i+1)
while len(q)!=1:
q.popleft()
if len(q) == 1:
break
q.append(q.popleft())
print(q[0])
Python
복사
10828. 스택
from sys import stdin
N = int(input())
stack = []
for _ in range(N):
a = stdin.readline().rstrip().split()
if a[0] == 'push':
stack.append(int(a[1]))
elif a[0] == 'pop':
if len(stack) == 0: print(-1)
else: print(stack.pop())
elif a[0] == 'size': print(len(stack))
elif a[0] == 'empty':
if len(stack) == 0: print(1)
else: print(0)
elif a[0] == 'top':
if len(stack) == 0: print(-1)
else: print(stack[-1])
Python
복사
1927. 최소 힙
from sys import stdin
N = int(stdin.readline())
queue = []
for _ in range(N):
n = int(stdin.readline())
#if 0 < n:
# queue.append(n)
if n == 0:
if len(queue) == 0:
print(0)
else: print(queue.pop(queue.index(min(queue))))
Python
복사
•
이미 x는 조건에서 2**31 보다 작은 자연수 또는 0이라고 했기 때문에 if 0 < n < 2**31 은 굳이 넣지 않아도 된다.
•
heapq 모듈을 사용하면 쉽게 구할 수 있다. (힙 정렬에 대한 이해도 필요)
# x가 자연수라면 배열에 x 추가
# x가 0이라면 가장 작은 값을 출력하고 그 값을 배열에서 제거 -> heapq 사용
from sys import stdin
import heapq
N = int(input())
heap = []
for _ in range(N):
a = int(stdin.readline())
if a != 0:
heapq.heappush(heap,a)
else:
try:
print(heapq.heappop(heap))
except:
print(0)
Python
복사