티스토리 뷰
문제 링크
24511번: queuestack
첫째 줄에 queuestack을 구성하는 자료구조의 개수 $N$이 주어진다. ($1 \leq N \leq 100\,000$) 둘째 줄에 길이 $N$의 수열 $A$가 주어진다. $i$번 자료구조가 큐라면 $A_i = 0$, 스택이라면 $A_i = 1$이다. 셋째 줄
www.acmicpc.net
문제 풀이
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
m = int(input())
c = list(map(int, input().split()))
answer = []
for i in range(n):
if a[i] == 0:
answer.append(b[i])
answer.reverse()
if answer == []:
print(*c)
else:
if m > len(answer):
for j in range(m - len(answer)):
answer.append(c[j])
print(*answer)
else:
print(*answer[0:m])
*key point: queuestack 안에 있는 자료구조들 중 스택의 경우, 원소 x를 삽입한 후 pop 하게 되어도 아무런 변화가 없다는 점을 이용한다. 스택인 경우를 무시하고 queuestack을 보게 되면, 결국 삽입한 원소가 appendleft 되고 가장 뒤쪽 원소가 pop되는 하나의 queue임을 알 수 있다. 이를 숙지하고 아래의 순서대로 알고리즘을 구현하였다.
1. 수열 A의 원소 중 0(큐)인 인덱스를 찾아서 수열 B의 해당 인덱스의 원소만 가지는 리스트(answer)를 만든 후 뒤집는다 (queuestack에서 원소가 나오는 순서대로 만드는 것) .
2. answer가 비어있는 경우는 queuestack 안의 모든 자료구조가 스택이므로 수열 C가 정답 리스트이다.
3. 그렇지 않은 경우 queuestack 안의 큐 자료구조의 원소가 역순으로 들어가 있는 answer 리스트를 원소의 수에 따라 조건을 나누어 부족한 만큼 수열 C의 원소로 채워주거나 불필요한 부분을 뺀 만큼만 출력한다.
*trials & comments:
import sys
from collections import deque
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
b = list(map(lambda x: deque([int(x)]), input().split()))
m = int(input())
c = list(map(int, input().split()))
result = []
for i in range(m):
x = c[i]
for j in range(n):
if a[j] == 0:
b[j].append(x)
x = b[j].popleft()
elif a[j] == 1:
b[j].append(x)
x = b[j].pop()
result.append(str(x))
print(" ".join(result))
문제 설명을 읽으며 그대로 풀이를 구현한 결과는 위와 같다. 이 경우 2중 for문에 의해 시간 복잡도가 크게 올라가서 시간 초과가 발생했다.
import sys
from collections import deque
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
m = int(input())
c = list(map(int, input().split()))
result = []
for i in range(m):
x = c[i]
for j in range(n):
if a[j] == 0:
b[j], x = x, b[j]
result.append(str(x))
print(" ".join(result))
스택인 경우는 생각할 필요가 없음을 깨닫고 append나 pop의 과정 또한 불필요함을 깨달아서 코드를 수정하였으나 아직 2중 for문의 굴레를 벗어나지 못해 시간 초과가 발생했다.
'What I Learned > Algorithm Practice' 카테고리의 다른 글
[백준 - python] 4779번: 칸토어 집합 (0) | 2024.04.04 |
---|---|
[백준 - python] 27433번: 팩토리얼 2 (0) | 2023.12.22 |
[백준 - python] 2346번: 풍선 터뜨리기 (1) | 2023.12.04 |
[백준 - python] 28279번: 덱 2 (0) | 2023.11.10 |
[백준 - python] 11866번: 요세푸스 문제 0 (0) | 2023.11.10 |
- Total
- Today
- Yesterday
- 항해 플러스
- 10807
- 5597
- 4134
- 2903
- 2053
- 1269
- 13241
- programmer
- 백준
- Python
- Programmers
- 13909
- 26069
- 2738
- 25192
- 25501
- SQL
- Wil
- 24723
- 벡준
- 항해+
- 20920
- 24060
- 24313
- 코육대
- til
- 17103
- 2587
- MySQL
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |