We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importsysclassDisjointSet:def__init__(self,n):self.parent=list(range(n+1))self.size=[1]*(n+1)deffind(self,x):ifself.parent[x]!=x:self.parent[x]=self.find(self.parent[x])returnself.parent[x]defunion(self,x,y):root_x=self.find(x)root_y=self.find(y)ifroot_x!=root_y:# Union by sizeifself.size[root_x]<self.size[root_y]:root_x,root_y=root_y,root_xself.parent[root_y]=root_xself.size[root_x]+=self.size[root_y]defsolve(N,queries):ds=DisjointSet(N)output=[]forqueryinqueries:ifquery[0]=='M':a,b=query[1],query[2]ds.union(a,b)elifquery[0]=='Q':x=query[1]output.append(ds.size[ds.find(x)])returnoutput
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Merging Communities
You are viewing a single comment's thread. Return to all comments →