| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
Tags
- 프로젝트
- github
- Git
- 백준
- 2주차
- js
- resnet50
- sql
- 정보처리기사실기
- re-id
- 파이썬
- 가상환경
- 프로그래머스
- Class
- 정보처리기사
- WIL
- vscode
- WHERE절
- REDIS
- poetry
- 장고
- 1주차
- channels
- 개발일지
- 미니프로젝트
- 알고리즘
- WebSocket
- Commpot
- 채팅
- 마스킹
Archives
- Today
- Total
개발일기
22. [백준] 스택과 AC문제 본문
먼저 문제풀이를 하고 스택과 큐, 덱 개념도 같이 살펴보자!!
1. 스택
https://www.acmicpc.net/problem/10828
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
스택 문제는 문제를 잘 읽고.. 이걸 코드로 잘 구현해주면 된다!
import sys;
input = sys.stdin.readline
stack = []
for _ in range(int(input())):
inputstr = input().split()
order = inputstr[0]
if order == 'push':
stack.append(inputstr[1])
if order == 'top' and len(stack)!=0:
print(stack[-1])
elif order == 'top' and len(stack) ==0:
print(-1)
if order == 'size':
print(len(stack))
if order == 'empty':
print(1) if len(stack)==0 else print(0)
if order == 'pop' and len(stack) != 0:
print(stack.pop())
elif order == 'pop' and len(stack) ==0:
print(-1)
try-except로 표현해줄 수도 있다.
if order == 'pop':
try:
print(stack.pop())
except IndexError:
print(-1)
코드의 길이를 간략하게 정리한다면,
import sys
input = sys.stdin.readline
stack =[]
for _ in range(int(input())):
inputstr = input().split()
order = inputstr[0]
if order == "push":
stack.append(inputstr[1])
elif order == "top":
print(stack[-1] if len(stack) else -1)
elif order == "size":
print(len(stack))
elif order == "empty":
print(0 if(len(stack)) else 1)
else: # order == 'pop'
try:
print(stack.pop())
except IndexError:
print(-1)
2. AC문제 - 시간초과때문에 고생했던 문제..
https://www.acmicpc.net/problem/5430
5430번: AC
각 테스트 케이스에 대해서, 입력으로 주어진 정수 배열에 함수를 수행한 결과를 출력한다. 만약, 에러가 발생한 경우에는 error를 출력한다.
www.acmicpc.net
휴.. 시간초과때문에 3번이나 빠꾸당함 ㅜㅜ
먼저 풀이를 공개하겠다..!
import sys;
input = sys.stdin.readline
from collections import deque
N = int(input().rstrip())
for _ in range(N):
order = list(input().rstrip())
n = int(input())
if n == 0:
input()
arr = deque()
else:
arr = deque(map(int, input().rstrip().lstrip('[').rstrip(']').split(',')))
noterror = True
direction = 0
for i in order:
if i == 'R':
if direction == 1:
direction = 0
else:
direction = 1
elif i == 'D':
try:
if direction == 0:
arr.popleft()
else:
arr.pop()
except:
noterror = False
print('error')
break
if noterror:
if direction == 0:
print("["+ ",".join(map(str, list(arr))) +"]")
else:
print("["+ ",".join(map(str, reversed(list(arr)))) +"]")
시간초과가 떴던 이유는, R(순서뒤집기)를 구현하는 과정에서 reverse를 사용했는데, 이렇게 하면 시간복잡도가 O(n)이라서 시간초과가 떴던 것이다.
해결방법은, direction이라는 변수를 이용해서 R을 표현했다.
direction = 0이 정방향, direction =1 이 한 번 순서 뒤집은 상태로 했고, 각 상황에 맞게 D(첫 숫자 버리기)와 리스트 구하는 걸 구현했다.
마지막에 리스트를 구하는 것에서 주의할 점은, 리스트 형태가 아니라 str 문자열로 구해야한다는 것..!!!
print(",".join(map(str, list(arr)))) # 3,4
print(type(",".join(map(str, list(arr))))) # <class 'str'>
print("["+ ",".join(map(str, list(arr))) +"]") # [3,4]
'오류 및 알고리즘정리본' 카테고리의 다른 글
| [Python] django.db.utils.OperationalError: no such table: 오류해결하기 (0) | 2023.06.08 |
|---|---|
| 21. [백준] 별찍기 7, 붙임성 좋은 총총이 (0) | 2023.06.01 |
| 20. [백준] 인사성 밝은 곰곰이/ 성택이의 은밀한 비밀번호/ 별찍기8 (0) | 2023.05.30 |
| 19. 백준 알고리즘 세금, 소수 찾기(에라토스테네스의 체) (0) | 2023.05.19 |
| 18. 백준 알고리즘 개, 별찍기 2 (0) | 2023.05.19 |