https://www.acmicpc.net/problem/11723
11723번: 집합
첫째 줄에 수행해야 하는 연산의 수 M (1 ≤ M ≤ 3,000,000)이 주어진다. 둘째 줄부터 M개의 줄에 수행해야 하는 연산이 한 줄에 하나씩 주어진다.
www.acmicpc.net
1.설명
일단 문제에서 집합에 따른 여러 조건들을 수행해야하는데 그렇게 어려워보이지않았습니다. 일단 실패한 코드 먼저 보시죠.
m = int(input())
s = set()
for _ in range(m):
arr = list(input().split())
c = arr[0]
if c == 'add':
s.add(int(arr[1]))
elif c == 'remove':
try:
s.remove(int(arr[1]))
except:
pass
elif c == 'check':
if int(arr[1]) in s:
print(1)
else:
print(0)
elif c == 'toggle':
if int(arr[1]) in s:
s.remove(int(arr[1]))
else:
s.add(int(arr[1]))
elif c == 'all':
s = set([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
else:
s = set()
코드상으로는 m번 실행하고 여러 조건들을 list로 받은뒤 split해 조건에 맞게 프로그램을 만들었습니다. 허나...
시간초과....
이런 경험이 처음이라 시간초과날때 해결방법을 찾아봤는데요
https://dailylifeofdeveloper.tistory.com/182
[Python] 시간 초과 날때 해결방법!
안녕하세요! daily_D 입니다! 👩🏻💻 오늘은 Python 으로 문제풀이할 때 시간초과가 나는 경우 해결할 수 있는 몇가지 방법을 알려드릴까합니다! 1. sys.stdin.readline()로 입력받기 입력값을 받아 저
dailylifeofdeveloper.tistory.com
이분 블로그에 잘 설명해주셔서 참고해서
sys 라는 파이썬의 표준 라이브러리를 사용하면 훨씬 빠른 시간에 적은 메모리를 사용하여 입력 받을 수 있답니다!
sys.stdin.readline로 입력받기를 사용해봤습니다!!
2.코드
import sys
input=sys.stdin.readline
chance = int(input())
s = set()
for _ in range(chance):
arr = list(input().split())
c = arr[0] #조건
if c == 'add': #더할때
s.add(int(arr[1]))
elif c == 'remove': #제거해야할때
try:
s.remove(int(arr[1]))
except:
pass
elif c == 'check': #있는지없는지확인
if int(arr[1]) in s:
print(1)
else:
print(0)
elif c == 'toggle': #있으면지우고없으면추가
if int(arr[1]) in s:
s.remove(int(arr[1]))
else:
s.add(int(arr[1]))
elif c == 'all':#1부터20
s = set([i for i in range(1,21)])
else:#전체제거
s = set()

'코딩test공부 > 백준python' 카테고리의 다른 글
10431.줄세우기 (0) | 2024.01.02 |
---|---|
9655. 돌게임 (0) | 2024.01.02 |
2941.크로아티아 알파벳 (1) | 2023.12.28 |
1157.단어공부 (0) | 2023.12.28 |
10818.최소,최대 (0) | 2023.12.27 |