from typing import Optional, List, Dict, Set class Heap: def __init__( self ) -> None: self.fro : List[ List[ int ] ] = [] self.to : List[ List[ int ] ] = [] def boundcheck( self, obj_id: int, index: int ) -> bool: return obj_id >= 0 and \ obj_id < len( self.to ) and \ index < len( self.to[ obj_id ] ) def read( self, obj_id: int, index: int ) -> Optional[int]: if not self.boundcheck( obj_id, index ): return None return self.to[ obj_id ][ index ] def write( self, obj_id: int, index: int, value: int ) -> bool: if not self.boundcheck( obj_id, index ): return False self.to[ obj_id ][ index ] = value return True def collect( self ) -> None: refmap : Dict[ int, int ] = {} self.fro = self.to self.to = [] self.copy( 0, refmap ) def copy( self, now: int, refmap: Dict[ int, int ] ) -> int: if now < 0: return now if now in refmap: return refmap[ now ] refmap[ now ] = len( self.to ) copy : List[ int ] = [] self.to.append( copy ) for val in self.fro[ now ]: copy.append( self.copy( val, refmap ) ) return refmap[ now ] def make( self, size: int ) -> int: self.to.append( [ 0 for _ in range( size ) ] ) return len( self.to ) - 1 import run_tests