

'''simple docstring'''


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




class     a			(				SCREAMING_SNAKE_CASE       ):






						"""simple docstring"""




						def __init__(							self					:      int  ):



								'''simple docstring'''



								self.test()







						def       __magic_name__							(							self					:      str  ):



								'''simple docstring'''



								snake_case__						:       int       						=  0
								snake_case__						:       Union[str, Any]       						=  False
								while not completed:
										if counter == 1:
												self.reset()
										snake_case__						:       List[str]       						=  self.advance()
										if not self.does_advance(snake_case_  ):
												raise Exception(
												    '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.'''  )

										snake_case__						,       snake_case__						,       snake_case__						:       int       						=  self.update(snake_case_  )
										counter += 1

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

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







						@abstractmethod
						def       __magic_name__							(							self					:      Any  ):



								'''simple docstring'''



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







						@abstractmethod
						def       __magic_name__							(							self					:      int			,			snake_case_					:      int  ):



								'''simple docstring'''



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







						@abstractmethod
						def       __magic_name__							(							self					:      List[Any]			,			snake_case_					:      int  ):



								'''simple docstring'''



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







						@abstractmethod
						def       __magic_name__							(							self					:      Optional[Any]  ):



								'''simple docstring'''



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







						@abstractmethod
						def       __magic_name__							(							self					:      Any  ):



								'''simple docstring'''



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







						@abstractmethod
						def       __magic_name__							(							self					:      Any			,			snake_case_					:      Any=False  ):



								'''simple docstring'''



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





class     a			(				SCREAMING_SNAKE_CASE       ):






						"""simple docstring"""




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



								'''simple docstring'''



								super(snake_case_			,			self  ).__init__()

								if not isinstance(snake_case_			,			snake_case_  ) or len(snake_case_  ) == 0:
										raise ValueError(F"""`token_ids` has to be a non-empty list, but is {token_ids}."""  )
								if any((not isinstance(snake_case_			,			snake_case_  ) 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}."""  )

								snake_case__						:       Optional[Any]       						=  token_ids

								snake_case__						:       Any       						=  len(self.token_ids  )
								snake_case__						:       Optional[int]       						=  -1  # the index of the currently fulfilled step
								snake_case__						:       Dict       						=  False







						def       __magic_name__							(							self					:      Optional[Any]  ):



								'''simple docstring'''



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







						def       __magic_name__							(							self					:      Dict			,			snake_case_					:      int  ):



								'''simple docstring'''



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

								if self.completed:
										return False

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







						def       __magic_name__							(							self					:      List[Any]			,			snake_case_					:      int  ):



								'''simple docstring'''



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

								snake_case__						:       Optional[Any]       						=  False
								snake_case__						:       Tuple       						=  False
								snake_case__						:       Optional[Any]       						=  False

								if self.does_advance(snake_case_  ):
										self.fulfilled_idx += 1
										snake_case__						:       str       						=  True
										if self.fulfilled_idx == (self.seqlen - 1):
												snake_case__						:       Optional[int]       						=  True
										snake_case__						:       List[str]       						=  completed
								else:
										# failed to make progress.
										snake_case__						:       Dict       						=  True
										self.reset()
								return stepped, completed, reset







						def       __magic_name__							(							self					:      Union[str, Any]  ):



								'''simple docstring'''



								snake_case__						:       Tuple       						=  False
								snake_case__						:       List[str]       						=  0







						def       __magic_name__							(							self					:      Any  ):



								'''simple docstring'''



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







						def       __magic_name__							(							self					:      str			,			snake_case_					:      Tuple=False  ):



								'''simple docstring'''



								snake_case__						:       Any       						=  PhrasalConstraint(self.token_ids  )

								if stateful:
										snake_case__						:       Optional[int]       						=  self.seqlen
										snake_case__						:       List[str]       						=  self.fulfilled_idx
										snake_case__						:       Union[str, Any]       						=  self.completed

								return new_constraint





class     a			:






						"""simple docstring"""




						def __init__(							self					:      Any			,			snake_case_					:      List[List[int]]			,			snake_case_					:      int=True  ):



								'''simple docstring'''



								snake_case__						:       List[str]       						=  max([len(snake_case_  ) for one in nested_token_ids]  )

								snake_case__						:       Tuple       						=  {}
								for token_ids in nested_token_ids:
										snake_case__						:       List[str]       						=  root
										for tidx, token_id in enumerate(snake_case_  ):
												if token_id not in level:
														snake_case__						:       int       						=  {}

												snake_case__						:       Union[str, Any]       						=  level[token_id]

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

								snake_case__						:       Optional[Any]       						=  root







						def       __magic_name__							(							self					:      Tuple			,			snake_case_					:      str  ):



								'''simple docstring'''



								snake_case__						:       Any       						=  self.trie

								for current_token in current_seq:
										snake_case__						:       str       						=  start[current_token]

								snake_case__						:       List[str]       						=  list(start.keys()  )

								return next_tokens







						def       __magic_name__							(							self					:      Optional[Any]			,			snake_case_					:      Dict  ):



								'''simple docstring'''



								snake_case__						:       Optional[int]       						=  self.next_tokens(snake_case_  )

								return len(snake_case_  ) == 0







						def       __magic_name__							(							self					:      List[Any]			,			snake_case_					:      Union[str, Any]  ):



								'''simple docstring'''



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







						def       __magic_name__							(							self					:      int			,			snake_case_					:      int			,			snake_case_					:      Optional[Any]  ):



								'''simple docstring'''



								snake_case__						:       Dict       						=  self.count_leaves(snake_case_  )
								return len(snake_case_  ) != leaf_count





class     a			(				SCREAMING_SNAKE_CASE       ):






						"""simple docstring"""




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



								'''simple docstring'''



								super(snake_case_			,			self  ).__init__()

								if not isinstance(snake_case_			,			snake_case_  ) or len(snake_case_  ) == 0:
										raise ValueError(F"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}."""  )
								if any(not isinstance(snake_case_			,			snake_case_  ) 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(snake_case_			,			snake_case_  ) 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}."""  )

								snake_case__						:       List[str]       						=  DisjunctiveTrie(snake_case_  )
								snake_case__						:       List[str]       						=  nested_token_ids

								snake_case__						:       int       						=  self.trie.max_height
								snake_case__						:       Dict       						=  []
								snake_case__						:       Optional[int]       						=  False







						def       __magic_name__							(							self					:      Optional[Any]  ):



								'''simple docstring'''



								snake_case__						:       int       						=  self.trie.next_tokens(self.current_seq  )

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







						def       __magic_name__							(							self					:      Any			,			snake_case_					:      int  ):



								'''simple docstring'''



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

								snake_case__						:       Tuple       						=  self.trie.next_tokens(self.current_seq  )

								return token_id in next_tokens







						def       __magic_name__							(							self					:      Union[str, Any]			,			snake_case_					:      int  ):



								'''simple docstring'''



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

								snake_case__						:       str       						=  False
								snake_case__						:       List[str]       						=  False
								snake_case__						:       Optional[int]       						=  False

								if self.does_advance(snake_case_  ):
										self.current_seq.append(snake_case_  )
										snake_case__						:       int       						=  True
								else:
										snake_case__						:       Optional[int]       						=  True
										self.reset()

								snake_case__						:       Tuple       						=  self.trie.reached_leaf(self.current_seq  )
								snake_case__						:       Optional[Any]       						=  completed

								return stepped, completed, reset







						def       __magic_name__							(							self					:      Optional[int]  ):



								'''simple docstring'''



								snake_case__						:       Dict       						=  False
								snake_case__						:       Dict       						=  []







						def       __magic_name__							(							self					:      Any  ):



								'''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       __magic_name__							(							self					:      Dict			,			snake_case_					:      Any=False  ):



								'''simple docstring'''



								snake_case__						:       int       						=  DisjunctiveConstraint(self.token_ids  )

								if stateful:
										snake_case__						:       Dict       						=  self.seqlen
										snake_case__						:       Optional[int]       						=  self.current_seq
										snake_case__						:       List[Any]       						=  self.completed

								return new_constraint





class     a			:






						"""simple docstring"""




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



								'''simple docstring'''



								snake_case__						:       List[Any]       						=  constraints

								# max # of steps required to fulfill a given constraint
								snake_case__						:       Union[str, Any]       						=  max([c.seqlen for c in constraints]  )
								snake_case__						:       Tuple       						=  len(snake_case_  )
								snake_case__						:       List[str]       						=  False

								self.init_state()







						def       __magic_name__							(							self					:      Any  ):



								'''simple docstring'''



								snake_case__						:       int       						=  []
								snake_case__						:       List[Any]       						=  None
								snake_case__						:       str       						=  [constraint.copy(stateful=snake_case_  ) for constraint in self.constraints]







						def       __magic_name__							(							self					:      Optional[int]  ):



								'''simple docstring'''



								snake_case__						:       Tuple       						=  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       __magic_name__							(							self					:      Dict  ):



								'''simple docstring'''



								snake_case__						:       Optional[int]       						=  []
								if self.inprogress_constraint is None:
										for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
												snake_case__						:       Optional[Any]       						=  constraint.advance()
												if isinstance(snake_case_			,			snake_case_  ):
														token_list.append(snake_case_  )
												elif isinstance(snake_case_			,			snake_case_  ):
														token_list.extend(snake_case_  )
								else:
										snake_case__						:       Tuple       						=  self.inprogress_constraint.advance()
										if isinstance(snake_case_			,			snake_case_  ):
												token_list.append(snake_case_  )
										elif isinstance(snake_case_			,			snake_case_  ):
												token_list.extend(snake_case_  )

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







						def       __magic_name__							(							self					:      Optional[Any]			,			snake_case_					:      Optional[List[int]]  ):



								'''simple docstring'''



								self.init_state()

								if token_ids is not None:
										for token in token_ids:
												# completes or steps **one** constraint
												snake_case__						,       snake_case__						:       Optional[int]       						=  self.add(snake_case_  )

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







						def       __magic_name__							(							self					:      Optional[int]			,			snake_case_					:      int  ):



								'''simple docstring'''



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

								snake_case__						,       snake_case__						:       Any       						=  False, False

								if self.completed:
										snake_case__						:       Union[str, Any]       						=  True
										snake_case__						:       Union[str, Any]       						=  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

										snake_case__						,       snake_case__						,       snake_case__						:       Union[str, Any]       						=  self.inprogress_constraint.update(snake_case_  )
										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=snake_case_  )  )
												snake_case__						:       Dict       						=  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  )
												snake_case__						:       str       						=  None

												if len(self.pending_constraints  ) == 0:
														# we're done!
														snake_case__						:       Dict       						=  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(snake_case_  ):
														snake_case__						,       snake_case__						,       snake_case__						:       List[Any]       						=  pending_constraint.update(snake_case_  )

														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(snake_case_  )
																snake_case__						:       List[Any]       						=  None

														if not complete and stepped:
																snake_case__						:       Any       						=  pending_constraint

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

																snake_case__						:       Optional[Any]       						=  (
																    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.

																		snake_case__						:       int       						=  True

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

								return complete, stepped







						def       __magic_name__							(							self					:      List[str]			,			snake_case_					:      str=True  ):



								'''simple docstring'''



								snake_case__						:       Optional[int]       						=  ConstraintListState(self.constraints  )  # we actually never though self.constraints objects
								# throughout this process. So it's at initialization state.

								if stateful:
										snake_case__						:       Any       						=  [
										    constraint.copy(stateful=snake_case_  ) for constraint in self.complete_constraints
										]
										if self.inprogress_constraint is not None:
												snake_case__						:       Union[str, Any]       						=  self.inprogress_constraint.copy(stateful=snake_case_  )
										snake_case__						:       Optional[int]       						=  [constraint.copy() for constraint in self.pending_constraints]

								return new_state






'''simple docstring'''


from bisect import bisect
from itertools import accumulate




def 	_a       (				__lowerCAmelCase		:      Optional[int]   ,							__lowerCAmelCase		:      Tuple   ,							__lowerCAmelCase		:      List[Any]   ,							__lowerCAmelCase		:      Optional[Any]     ):

		"""simple docstring"""

		snake_case__						:       Any       						=  sorted(zip(__lowerCAmelCase   ,							__lowerCAmelCase     )   ,							key=lambda __lowerCAmelCase     : x[0] / x[1]   ,							reverse=__lowerCAmelCase     )
		snake_case__						,       snake_case__						:       Union[str, Any]       						=  [i[0] for i in r], [i[1] for i in r]
		snake_case__						:       Dict       						=  list(accumulate(__lowerCAmelCase     )     )
		snake_case__						:       Optional[int]       						=  bisect(__lowerCAmelCase   ,							__lowerCAmelCase     )
		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()



