Baekjun #1717 was being solved. I was solving it using the Disjoint-set data structure, but when I received the input as input(), there was a time-out error, referring to the other minutes, and then sys after import sys.Using stdin.readline() saves a lot of time. I wonder how these two functions work differently, and how the time difference is like this. Below is the code you used to solve the problem.
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 : # When not in the same set
If heightList[A] == heightList[B] : #If they are the same height
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: # Add Set
sumSet(a,b)
else : #Confirm existence
findSet(a,b)
Someone posted a similar question on acmicpc.
I think Jonas answered, so why don't you refer to this?
© 2024 OneMinuteCode. All rights reserved.