Advertisement
kosievdmerwe

Untitled

Nov 22nd, 2021
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. class UnionFind:
  2.     def __init__(self):
  3.         self.parent = self
  4.         self.size = 1
  5.    
  6.     def get_root(self) -> "UnionFind":
  7.         if self.parent is self:
  8.             return self
  9.        
  10.         self.parent = self.parent.get_root()
  11.         return self.parent
  12.    
  13.     def union(self, other: "UnionFind") -> None:
  14.         root_large = self.get_root()
  15.         root_small = other.get_root()
  16.         if root_large is root_small:
  17.             return
  18.        
  19.         if root_small.size > root_large.size:
  20.             root_large, root_small = root_small, root_large
  21.        
  22.         root_small.parent = root_large
  23.         root_large.size += root_small.size
  24.        
  25.        
  26. class Solution:
  27.     def largestComponentSize(self, nums: List[int]) -> int:
  28.         N = max(nums)
  29.         nums = set(nums)
  30.        
  31.         ufs = {n: UnionFind() for n in nums}
  32.         prime_ufs = {}
  33.        
  34.         sieve = [True] * (N + 1)
  35.         sieve[0] = sieve[1] = False
  36.         for p in range(2, N + 1):
  37.             if not sieve[p]:
  38.                 continue
  39.            
  40.             for n in range(p, N + 1, p):
  41.                 sieve[n] = False
  42.                 if n not in nums:
  43.                     continue
  44.                
  45.                 uf = ufs[n]
  46.                 if p not in prime_ufs:
  47.                     prime_ufs[p] = uf
  48.                 else:
  49.                     prime_ufs[p].union(uf)
  50.                    
  51.         return max(
  52.             uf.get_root().size for uf in ufs.values()
  53.         )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement