Python3에서 input()함수와 sys.stdin.readline()은 어떻게 작동하길래 속도차이가 이렇게 심하게 나는 건가요?
조회수 4325회
백준 1717번을 풀고 있었습니다. Disjoint-set data structure 을 이용해서 풀고 있었는데, 입력을 input()으로 받을 때는 시간초과 오류가 나더니, 다른 분 풀이를 참고하여 import sys 후 sys.stdin.readline()을 사용하니 훨씬 시간이 단축 되었습니다. 이 두 함수의 작동 방식이 어떻게 다르길래 시간 차이가 이렇게 나는 지 궁금합니다. 아래는 문제를 풀었을 때 사용한 코드입니다.
import random
import sys
n,m = map(int,sys.stdin.readline().split())
parentList = [i for i in range(n+1)]
heightList = [0 for _ in range(n+1)]
def findParent(a) :
if parentList[a] == a :
return a
else :
parentList[a] = findParent(parentList[a])
return parentList[a]
def sumSet(a,b):
A = findParent(a)
B = findParent(b)
if A == B:
pass
else : # 같은 집합에 있지 않을 때
if heightList[A] == heightList[B] : #둘이 높이가 같은 경우
if random.randint(0,2) == 1:
parentList[B] = A
heightList[A] += 1
else:
parentList[A] = B
heightList[B] += 1
elif heightList[A] > heightList[B]:
parentList[B] = A
else :
parentList[A] = B
def findSet(a,b):
A = findParent(a)
B = findParent(b)
if A == B:
print('YES')
else :
print('NO')
for i in range(m):
op,a,b = map(int,sys.stdin.readline().split())
if op == 0: # 집합 더하기
sumSet(a,b)
else : #존재 확인
findSet(a,b)
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력