from abc import ABC, abstractmethod
from typing import List, Optional




class    a__				(       UpperCAmelCase__			):






     def __init__(			self		:		Dict   ):





         """simple docstring"""



         self.test()






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[str]   ):





         """simple docstring"""



         __lowerCamelCase          =  0
         __lowerCamelCase          =  False
         while not completed:
             if counter == 1:
                 self.reset()
             __lowerCamelCase          =  self.advance()
             if not self.does_advance(a   ):
                 raise Exception(
                     '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.'''   )

             __lowerCamelCase     ,  __lowerCamelCase     ,  __lowerCamelCase          =  self.update(a   )
             counter += 1

             if counter > 1_00_00:
                 raise Exception('''update() does not fulfill the constraint.'''   )

         if self.remaining() != 0:
             raise Exception('''Custom Constraint is not defined correctly.'''   )






     @abstractmethod
     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]   ):





         """simple docstring"""



         raise NotImplementedError(
             f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""   )






     @abstractmethod
     def        SCREAMING_SNAKE_CASE__       (			self		:		int  ,    a		:		int   ):





         """simple docstring"""



         raise NotImplementedError(
             f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""   )






     @abstractmethod
     def        SCREAMING_SNAKE_CASE__       (			self		:		List[str]  ,    a		:		int   ):





         """simple docstring"""



         raise NotImplementedError(
             f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""   )






     @abstractmethod
     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple   ):





         """simple docstring"""



         raise NotImplementedError(
             f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""   )






     @abstractmethod
     def        SCREAMING_SNAKE_CASE__       (			self		:		Union[str, Any]   ):





         """simple docstring"""



         raise NotImplementedError(
             f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""   )






     @abstractmethod
     def        SCREAMING_SNAKE_CASE__       (			self		:		Dict  ,    a		:		Dict=False   ):





         """simple docstring"""



         raise NotImplementedError(
             f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""   )




class    a__				(       UpperCAmelCase__			):






     def __init__(			self		:		Union[str, Any]  ,    a		:		List[int]   ):





         """simple docstring"""



         super(a  ,    self   ).__init__()

         if not isinstance(a  ,    a   ) or len(a   ) == 0:
             raise ValueError(f"""`token_ids` has to be a non-empty list, but is {token_ids}."""   )
         if any((not isinstance(a  ,    a   ) or token_id < 0) for token_id in token_ids   ):
             raise ValueError(f"""Each list in `token_ids` has to be a list of positive integers, but is {token_ids}."""   )

         __lowerCamelCase          =  token_ids

         __lowerCamelCase          =  len(self.token_ids   )
         __lowerCamelCase          =  -1  # the index of the currently fulfilled step
         __lowerCamelCase          =  False






     def        SCREAMING_SNAKE_CASE__       (			self		:		Any   ):





         """simple docstring"""



         if self.completed:
             return None
         return self.token_ids[self.fulfilled_idx + 1]






     def        SCREAMING_SNAKE_CASE__       (			self		:		Any  ,    a		:		int   ):





         """simple docstring"""



         if not isinstance(a  ,    a   ):
             raise ValueError(f"""`token_id` has to be an `int`, but is {token_id} of type {type(a   )}"""   )

         if self.completed:
             return False

         return token_id == self.token_ids[self.fulfilled_idx + 1]






     def        SCREAMING_SNAKE_CASE__       (			self		:		int  ,    a		:		int   ):





         """simple docstring"""



         if not isinstance(a  ,    a   ):
             raise ValueError(f"""`token_id` has to be an `int`, but is {token_id} of type {type(a   )}"""   )

         __lowerCamelCase          =  False
         __lowerCamelCase          =  False
         __lowerCamelCase          =  False

         if self.does_advance(a   ):
             self.fulfilled_idx += 1
             __lowerCamelCase          =  True
             if self.fulfilled_idx == (self.seqlen - 1):
                 __lowerCamelCase          =  True
             __lowerCamelCase          =  completed
         else:
             # failed to make progress.
             __lowerCamelCase          =  True
             self.reset()
         return stepped, completed, reset






     def        SCREAMING_SNAKE_CASE__       (			self		:		Dict   ):





         """simple docstring"""



         __lowerCamelCase          =  False
         __lowerCamelCase          =  0






     def        SCREAMING_SNAKE_CASE__       (			self		:		int   ):





         """simple docstring"""



         return self.seqlen - (self.fulfilled_idx + 1)






     def        SCREAMING_SNAKE_CASE__       (			self		:		Any  ,    a		:		Any=False   ):





         """simple docstring"""



         __lowerCamelCase          =  PhrasalConstraint(self.token_ids   )

         if stateful:
             __lowerCamelCase          =  self.seqlen
             __lowerCamelCase          =  self.fulfilled_idx
             __lowerCamelCase          =  self.completed

         return new_constraint




class    a__				:






     def __init__(			self		:		str  ,    a		:		List[List[int]]  ,    a		:		List[str]=True   ):





         """simple docstring"""



         __lowerCamelCase          =  max([len(a   ) for one in nested_token_ids]   )

         __lowerCamelCase          =  {}
         for token_ids in nested_token_ids:
             __lowerCamelCase          =  root
             for tidx, token_id in enumerate(a   ):
                 if token_id not in level:
                     __lowerCamelCase          =  {}

                 __lowerCamelCase          =  level[token_id]

         if no_subsets and self.has_subsets(a  ,    a   ):
             raise ValueError(
                 '''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is'''
                 f""" {nested_token_ids}."""   )

         __lowerCamelCase          =  root






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]  ,    a		:		Any   ):





         """simple docstring"""



         __lowerCamelCase          =  self.trie

         for current_token in current_seq:
             __lowerCamelCase          =  start[current_token]

         __lowerCamelCase          =  list(start.keys()   )

         return next_tokens






     def        SCREAMING_SNAKE_CASE__       (			self		:		Dict  ,    a		:		Tuple   ):





         """simple docstring"""



         __lowerCamelCase          =  self.next_tokens(a   )

         return len(a   ) == 0






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]  ,    a		:		List[str]   ):





         """simple docstring"""



         __lowerCamelCase          =  list(root.values()   )
         if len(a   ) == 0:
             return 1
         else:
             return sum([self.count_leaves(a   ) for nn in next_nodes]   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[str]  ,    a		:		Union[str, Any]  ,    a		:		Tuple   ):





         """simple docstring"""



         __lowerCamelCase          =  self.count_leaves(a   )
         return len(a   ) != leaf_count




class    a__				(       UpperCAmelCase__			):






     def __init__(			self		:		Optional[Any]  ,    a		:		List[List[int]]   ):





         """simple docstring"""



         super(a  ,    self   ).__init__()

         if not isinstance(a  ,    a   ) or len(a   ) == 0:
             raise ValueError(f"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}."""   )
         if any(not isinstance(a  ,    a   ) for token_ids in nested_token_ids   ):
             raise ValueError(f"""`nested_token_ids` has to be a list of lists, but is {nested_token_ids}."""   )
         if any(
             any((not isinstance(a  ,    a   ) or token_id < 0) for token_id in token_ids   )
             for token_ids in nested_token_ids   ):
             raise ValueError(
                 f"""Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}."""   )

         __lowerCamelCase          =  DisjunctiveTrie(a   )
         __lowerCamelCase          =  nested_token_ids

         __lowerCamelCase          =  self.trie.max_height
         __lowerCamelCase          =  []
         __lowerCamelCase          =  False






     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple   ):





         """simple docstring"""



         __lowerCamelCase          =  self.trie.next_tokens(self.current_seq   )

         if len(a   ) == 0:
             return None
         else:
             return token_list






     def        SCREAMING_SNAKE_CASE__       (			self		:		int  ,    a		:		int   ):





         """simple docstring"""



         if not isinstance(a  ,    a   ):
             raise ValueError(f"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(a   )}"""   )

         __lowerCamelCase          =  self.trie.next_tokens(self.current_seq   )

         return token_id in next_tokens






     def        SCREAMING_SNAKE_CASE__       (			self		:		Any  ,    a		:		int   ):





         """simple docstring"""



         if not isinstance(a  ,    a   ):
             raise ValueError(f"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(a   )}"""   )

         __lowerCamelCase          =  False
         __lowerCamelCase          =  False
         __lowerCamelCase          =  False

         if self.does_advance(a   ):
             self.current_seq.append(a   )
             __lowerCamelCase          =  True
         else:
             __lowerCamelCase          =  True
             self.reset()

         __lowerCamelCase          =  self.trie.reached_leaf(self.current_seq   )
         __lowerCamelCase          =  completed

         return stepped, completed, reset






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]   ):





         """simple docstring"""



         __lowerCamelCase          =  False
         __lowerCamelCase          =  []






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]   ):





         """simple docstring"""



         if self.completed:
             # since this can be completed without reaching max height
             return 0
         else:
             return self.seqlen - len(self.current_seq   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple  ,    a		:		Dict=False   ):





         """simple docstring"""



         __lowerCamelCase          =  DisjunctiveConstraint(self.token_ids   )

         if stateful:
             __lowerCamelCase          =  self.seqlen
             __lowerCamelCase          =  self.current_seq
             __lowerCamelCase          =  self.completed

         return new_constraint




class    a__				:






     def __init__(			self		:		List[Any]  ,    a		:		List[Constraint]   ):





         """simple docstring"""



         __lowerCamelCase          =  constraints

         # max # of steps required to fulfill a given constraint
         __lowerCamelCase          =  max([c.seqlen for c in constraints]   )
         __lowerCamelCase          =  len(a   )
         __lowerCamelCase          =  False

         self.init_state()






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  []
         __lowerCamelCase          =  None
         __lowerCamelCase          =  [constraint.copy(stateful=a   ) for constraint in self.constraints]






     def        SCREAMING_SNAKE_CASE__       (			self		:		str   ):





         """simple docstring"""



         __lowerCamelCase          =  0
         if self.inprogress_constraint:
             # extra points for having a constraint mid-fulfilled
             add += self.max_seqlen - self.inprogress_constraint.remaining()

         return (len(self.complete_constraints   ) * self.max_seqlen) + add






     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple   ):





         """simple docstring"""



         __lowerCamelCase          =  []
         if self.inprogress_constraint is None:
             for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
                 __lowerCamelCase          =  constraint.advance()
                 if isinstance(a  ,    a   ):
                     token_list.append(a   )
                 elif isinstance(a  ,    a   ):
                     token_list.extend(a   )
         else:
             __lowerCamelCase          =  self.inprogress_constraint.advance()
             if isinstance(a  ,    a   ):
                 token_list.append(a   )
             elif isinstance(a  ,    a   ):
                 token_list.extend(a   )

         if len(a   ) == 0:
             return None
         else:
             return token_list






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]  ,    a		:		Optional[List[int]]   ):





         """simple docstring"""



         self.init_state()

         if token_ids is not None:
             for token in token_ids:
                 # completes or steps **one** constraint
                 __lowerCamelCase     ,  __lowerCamelCase          =  self.add(a   )

                 # the entire list of constraints are fulfilled
                 if self.completed:
                     break






     def        SCREAMING_SNAKE_CASE__       (			self		:		int  ,    a		:		int   ):





         """simple docstring"""



         if not isinstance(a  ,    a   ):
             raise ValueError(f"""`token_id` should be an `int`, but is `{token_id}`."""   )

         __lowerCamelCase     ,  __lowerCamelCase          =  False, False

         if self.completed:
             __lowerCamelCase          =  True
             __lowerCamelCase          =  False
             return complete, stepped

         if self.inprogress_constraint is not None:
             # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
             # job, simply update the state

             __lowerCamelCase     ,  __lowerCamelCase     ,  __lowerCamelCase          =  self.inprogress_constraint.update(a   )
             if reset:
                 # 1. If the next token breaks the progress, then we must restart.
                 #     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

                 #     But that doesn't mean we self.init_state(), since we only reset the state for this particular
                 #     constraint, not the full list of constraints.

                 self.pending_constraints.append(self.inprogress_constraint.copy(stateful=a   )   )
                 __lowerCamelCase          =  None

             if complete:
                 # 2. If the next token completes the constraint, move it to completed list, set
                 #     inprogress to None. If there are no pending constraints either, then this full list of constraints
                 #     is complete.

                 self.complete_constraints.append(self.inprogress_constraint   )
                 __lowerCamelCase          =  None

                 if len(self.pending_constraints   ) == 0:
                     # we're done!
                     __lowerCamelCase          =  True

         else:
             # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
             # of constraints?

             for cidx, pending_constraint in enumerate(self.pending_constraints   ):
                 if pending_constraint.does_advance(a   ):
                     __lowerCamelCase     ,  __lowerCamelCase     ,  __lowerCamelCase          =  pending_constraint.update(a   )

                     if not stepped:
                         raise Exception(
                             '''`constraint.update(token_id)` is not yielding incremental progress, '''
                             '''even though `constraint.does_advance(token_id)` is true.'''   )

                     if complete:
                         self.complete_constraints.append(a   )
                         __lowerCamelCase          =  None

                     if not complete and stepped:
                         __lowerCamelCase          =  pending_constraint

                     if complete or stepped:
                         # If we made any progress at all, then it's at least not a "pending constraint".

                         __lowerCamelCase          =  (
                             self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
                         )

                         if len(self.pending_constraints   ) == 0 and self.inprogress_constraint is None:
                             # If there's no longer any pending after this and no inprogress either, then we must be
                             # complete.

                             __lowerCamelCase          =  True

                         break  # prevent accidentally stepping through multiple constraints with just one token.

         return complete, stepped






     def        SCREAMING_SNAKE_CASE__       (			self		:		Dict  ,    a		:		int=True   ):





         """simple docstring"""



         __lowerCamelCase          =  ConstraintListState(self.constraints   )  # we actually never though self.constraints objects
         # throughout this process. So it's at initialization state.

         if stateful:
             __lowerCamelCase          =  [
                 constraint.copy(stateful=a   ) for constraint in self.complete_constraints
             ]
             if self.inprogress_constraint is not None:
                 __lowerCamelCase          =  self.inprogress_constraint.copy(stateful=a   )
             __lowerCamelCase          =  [constraint.copy() for constraint in self.pending_constraints]

         return new_state

'''simple docstring'''




from bisect import bisect
from itertools import accumulate






def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    )     ->   str:
    __lowerCamelCase          =  sorted(zip(UpperCamelCase__    ,  UpperCamelCase__    )    ,  key=lambda UpperCamelCase__    : x[0] / x[1]    ,  reverse=UpperCamelCase__    )
    __lowerCamelCase     ,  __lowerCamelCase          =  [i[0] for i in r], [i[1] for i in r]
    __lowerCamelCase          =  list(accumulate(UpperCamelCase__    )    )
    __lowerCamelCase          =  bisect(UpperCamelCase__    ,  UpperCamelCase__    )
    return (
        0
        if k == 0
        else sum(vl[:k]    ) + (w - acc[k - 1]) * (vl[k]) / (wt[k])
        if k != n
        else sum(vl[:k]    )
    )


if __name__ == "__main__":
  import doctest

  doctest.testmod()
