


import argparse

import torch

from diffusers import UNetaDConditionModel

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      List[str]     ,					UpperCamelCase		:      Any     ,					UpperCamelCase		:      int     ,					UpperCamelCase		:      Union[str, Any]=None     ,					UpperCamelCase		:      Optional[int]=None     ,					UpperCamelCase		:      int=None	)     ->	Dict:



	"""simple docstring"""






	assert isinstance(UpperCamelCase     ,					UpperCamelCase	), "Paths should be a list of dicts containing 'old' and 'new' keys."

	# Splits the attention layers into three variables.
	if attention_paths_to_split is not None:
		for path, path_map in attention_paths_to_split.items():
			a_     			=   old_checkpoint[path]
			a_     			=   old_tensor.shape[0] // 3

			a_     			=   (-1, channels) if len(old_tensor.shape	) == 3 else (-1)

			a_     			=   old_tensor.shape[0] // config["""num_head_channels"""] // 3

			a_     			=   old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:]	)
			a_			, a_			, a_     			=   old_tensor.split(channels // num_heads     ,					dim=1	)

			a_     			=   query.reshape(UpperCamelCase	)
			a_     			=   key.reshape(UpperCamelCase	)
			a_     			=   value.reshape(UpperCamelCase	)

	for path in paths:
		a_     			=   path["""new"""]

		# These have already been assigned
		if attention_paths_to_split is not None and new_path in attention_paths_to_split:
			continue

		if additional_replacements is not None:
			for replacement in additional_replacements:
				a_     			=   new_path.replace(replacement["""old"""]     ,					replacement["""new"""]	)

        # proj_attn.weight has to be converted from conv 1D to linear
		a_     			=   old_checkpoint[path["""old"""]]
		a_     			=   ["""proj_attn.weight"""]
		a_     			=   ["""proj_out.weight""", """proj_in.weight"""]
		if any(k in new_path for k in names	):
			a_     			=   weight[:, :, 0]
		elif any(k in new_path for k in names_a	) and len(weight.shape	) > 2 and ".attentions." not in new_path:
			a_     			=   weight[:, :, 0]
		else:
			a_     			=   weight

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      List[Any]     ,					UpperCamelCase		:      Optional[int]=0	)     ->	List[str]:



	"""simple docstring"""






	a_     			=   []
	for old_item in old_list:
		a_     			=   old_item

		#         new_item = new_item.replace('norm.weight', 'group_norm.weight')
		#         new_item = new_item.replace('norm.bias', 'group_norm.bias')

		#         new_item = new_item.replace('proj_out.weight', 'proj_attn.weight')
		#         new_item = new_item.replace('proj_out.bias', 'proj_attn.bias')

		#         new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)

		mapping.append({"""old""": old_item, """new""": new_item}	)

	return mapping

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      Optional[Any]     ,					UpperCamelCase		:      Any=1	)     ->	Optional[int]:



	"""simple docstring"""






	if n_shave_prefix_segments >= 0:
		return ".".join(path.split("""."""	)[n_shave_prefix_segments:]	)
	else:
		return ".".join(path.split("""."""	)[:n_shave_prefix_segments]	)

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      Any     ,					UpperCamelCase		:      Union[str, Any]=0	)     ->	Tuple:



	"""simple docstring"""






	a_     			=   []
	for old_item in old_list:
		mapping.append({"""old""": old_item, """new""": old_item}	)

	return mapping

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      List[Any]     ,					UpperCamelCase		:      Optional[int]=0	)     ->	Optional[int]:



	"""simple docstring"""






	a_     			=   []
	for old_item in old_list:
		a_     			=   old_item.replace("""in_layers.0"""     ,					"""norm1"""	)
		a_     			=   new_item.replace("""in_layers.2"""     ,					"""conv1"""	)

		a_     			=   new_item.replace("""out_layers.0"""     ,					"""norm2"""	)
		a_     			=   new_item.replace("""out_layers.3"""     ,					"""conv2"""	)

		a_     			=   new_item.replace("""emb_layers.1"""     ,					"""time_emb_proj"""	)
		a_     			=   new_item.replace("""skip_connection"""     ,					"""conv_shortcut"""	)

		a_     			=   shave_segments(UpperCamelCase     ,					n_shave_prefix_segments=UpperCamelCase	)

		if "temopral_conv" not in old_item:
			mapping.append({"""old""": old_item, """new""": new_item}	)

	return mapping

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      Any     ,					UpperCamelCase		:      Tuple     ,					UpperCamelCase		:      Tuple=None     ,					UpperCamelCase		:      int=False	)     ->	List[Any]:



	"""simple docstring"""






	a_     			=   {}
	a_     			=   list(checkpoint.keys()	)

	a_     			=   """model.diffusion_model."""

	# at least a 100 parameters have to start with `model_ema` in order for the checkpoint to be EMA
	if sum(k.startswith("""model_ema"""	) for k in keys	) > 100 and extract_ema:
		print(F"""Checkpoint {path} has both EMA and non-EMA weights."""	)
		print(
		    """In this conversion only the EMA weights are extracted. If you want to instead extract the non-EMA"""
		    """ weights (useful to continue fine-tuning), please make sure to remove the `--extract_ema` flag."""	)
		for key in keys:
			if key.startswith("""model.diffusion_model"""	):
				a_     			=   """model_ema.""" + """""".join(key.split("""."""	)[1:]	)
				a_     			=   checkpoint.pop(UpperCamelCase	)
	else:
		if sum(k.startswith("""model_ema"""	) for k in keys	) > 100:
			print(
			    """In this conversion only the non-EMA weights are extracted. If you want to instead extract the EMA"""
			    """ weights (usually better for inference), please make sure to add the `--extract_ema` flag."""	)

		for key in keys:
			a_     			=   checkpoint.pop(UpperCamelCase	)

	a_     			=   {}

	a_     			=   unet_state_dict["""time_embed.0.weight"""]
	a_     			=   unet_state_dict["""time_embed.0.bias"""]
	a_     			=   unet_state_dict["""time_embed.2.weight"""]
	a_     			=   unet_state_dict["""time_embed.2.bias"""]

	if config["class_embed_type"] is None:
		# No parameters to port
		...
	elif config["class_embed_type"] == "timestep" or config["class_embed_type"] == "projection":
		a_     			=   unet_state_dict["""label_emb.0.0.weight"""]
		a_     			=   unet_state_dict["""label_emb.0.0.bias"""]
		a_     			=   unet_state_dict["""label_emb.0.2.weight"""]
		a_     			=   unet_state_dict["""label_emb.0.2.bias"""]
	else:
		raise NotImplementedError(F"""Not implemented `class_embed_type`: {config["class_embed_type"]}"""	)

	a_     			=   unet_state_dict["""input_blocks.0.0.weight"""]
	a_     			=   unet_state_dict["""input_blocks.0.0.bias"""]

	a_     			=   [v for v in unet_state_dict if v.startswith("""input_blocks.0.1"""	)]
	a_     			=   renew_attention_paths(UpperCamelCase	)
	a_     			=   {"""old""": """input_blocks.0.1""", """new""": """transformer_in"""}
	assign_to_checkpoint(UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					additional_replacements=[meta_path]     ,					config=UpperCamelCase	)

	a_     			=   unet_state_dict["""out.0.weight"""]
	a_     			=   unet_state_dict["""out.0.bias"""]
	a_     			=   unet_state_dict["""out.2.weight"""]
	a_     			=   unet_state_dict["""out.2.bias"""]

	# Retrieves the keys for the input blocks only
	a_     			=   len({""".""".join(layer.split("""."""	)[:2]	) for layer in unet_state_dict if """input_blocks""" in layer}	)
	a_     			=   {
	    layer_id: [key for key in unet_state_dict if F"""input_blocks.{layer_id}""" in key]
	    for layer_id in range(UpperCamelCase	)
	}

	# Retrieves the keys for the middle blocks only
	a_     			=   len({""".""".join(layer.split("""."""	)[:2]	) for layer in unet_state_dict if """middle_block""" in layer}	)
	a_     			=   {
	    layer_id: [key for key in unet_state_dict if F"""middle_block.{layer_id}""" in key]
	    for layer_id in range(UpperCamelCase	)
	}

	# Retrieves the keys for the output blocks only
	a_     			=   len({""".""".join(layer.split("""."""	)[:2]	) for layer in unet_state_dict if """output_blocks""" in layer}	)
	a_     			=   {
	    layer_id: [key for key in unet_state_dict if F"""output_blocks.{layer_id}""" in key]
	    for layer_id in range(UpperCamelCase	)
	}

	for i in range(1     ,					UpperCamelCase	):
		a_     			=   (i - 1) // (config["""layers_per_block"""] + 1)
		a_     			=   (i - 1) % (config["""layers_per_block"""] + 1)

		a_     			=   [
		    key for key in input_blocks[i] if F"""input_blocks.{i}.0""" in key and F"""input_blocks.{i}.0.op""" not in key
		]
		a_     			=   [key for key in input_blocks[i] if F"""input_blocks.{i}.1""" in key]
		a_     			=   [key for key in input_blocks[i] if F"""input_blocks.{i}.2""" in key]

		if F"""input_blocks.{i}.op.weight""" in unet_state_dict:
			a_     			=   unet_state_dict.pop(
			    F"""input_blocks.{i}.op.weight"""	)
			a_     			=   unet_state_dict.pop(
			    F"""input_blocks.{i}.op.bias"""	)

		a_     			=   renew_resnet_paths(UpperCamelCase	)
		a_     			=   {"""old""": F"""input_blocks.{i}.0""", """new""": F"""down_blocks.{block_id}.resnets.{layer_in_block_id}"""}
		assign_to_checkpoint(
		    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					additional_replacements=[meta_path]     ,					config=UpperCamelCase	)

		a_     			=   [key for key in resnets if """temopral_conv""" in key]
		a_     			=   renew_temp_conv_paths(UpperCamelCase	)
		a_     			=   {
		    """old""": F"""input_blocks.{i}.0.temopral_conv""",
		    """new""": F"""down_blocks.{block_id}.temp_convs.{layer_in_block_id}""",
		}
		assign_to_checkpoint(
		    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					additional_replacements=[meta_path]     ,					config=UpperCamelCase	)

		if len(UpperCamelCase	):
			a_     			=   renew_attention_paths(UpperCamelCase	)
			a_     			=   {"""old""": F"""input_blocks.{i}.1""", """new""": F"""down_blocks.{block_id}.attentions.{layer_in_block_id}"""}
			assign_to_checkpoint(
			    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					additional_replacements=[meta_path]     ,					config=UpperCamelCase	)

		if len(UpperCamelCase	):
			a_     			=   renew_attention_paths(UpperCamelCase	)
			a_     			=   {
			    """old""": F"""input_blocks.{i}.2""",
			    """new""": F"""down_blocks.{block_id}.temp_attentions.{layer_in_block_id}""",
			}
			assign_to_checkpoint(
			    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					additional_replacements=[meta_path]     ,					config=UpperCamelCase	)

	a_     			=   middle_blocks[0]
	a_     			=   [key for key in resnet_a if """temopral_conv""" in key]
	a_     			=   middle_blocks[1]
	a_     			=   middle_blocks[2]
	a_     			=   middle_blocks[3]
	a_     			=   [key for key in resnet_a if """temopral_conv""" in key]

	a_     			=   renew_resnet_paths(UpperCamelCase	)
	a_     			=   {"""old""": """middle_block.0""", """new""": """mid_block.resnets.0"""}
	assign_to_checkpoint(
	    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					config=UpperCamelCase     ,					additional_replacements=[meta_path]	)

	a_     			=   renew_temp_conv_paths(UpperCamelCase	)
	a_     			=   {"""old""": """middle_block.0.temopral_conv""", """new""": """mid_block.temp_convs.0"""}
	assign_to_checkpoint(
	    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					config=UpperCamelCase     ,					additional_replacements=[meta_path]	)

	a_     			=   renew_resnet_paths(UpperCamelCase	)
	a_     			=   {"""old""": """middle_block.3""", """new""": """mid_block.resnets.1"""}
	assign_to_checkpoint(
	    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					config=UpperCamelCase     ,					additional_replacements=[meta_path]	)

	a_     			=   renew_temp_conv_paths(UpperCamelCase	)
	a_     			=   {"""old""": """middle_block.3.temopral_conv""", """new""": """mid_block.temp_convs.1"""}
	assign_to_checkpoint(
	    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					config=UpperCamelCase     ,					additional_replacements=[meta_path]	)

	a_     			=   renew_attention_paths(UpperCamelCase	)
	a_     			=   {"""old""": """middle_block.1""", """new""": """mid_block.attentions.0"""}
	assign_to_checkpoint(
	    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					additional_replacements=[meta_path]     ,					config=UpperCamelCase	)

	a_     			=   renew_attention_paths(UpperCamelCase	)
	a_     			=   {"""old""": """middle_block.2""", """new""": """mid_block.temp_attentions.0"""}
	assign_to_checkpoint(
	    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					additional_replacements=[meta_path]     ,					config=UpperCamelCase	)

	for i in range(UpperCamelCase	):
		a_     			=   i // (config["""layers_per_block"""] + 1)
		a_     			=   i % (config["""layers_per_block"""] + 1)
		a_     			=   [shave_segments(UpperCamelCase     ,					2	) for name in output_blocks[i]]
		a_     			=   {}

		for layer in output_block_layers:
			a_			, a_     			=   layer.split("""."""	)[0], shave_segments(UpperCamelCase     ,					1	)
			if layer_id in output_block_list:
				output_block_list[layer_id].append(UpperCamelCase	)
			else:
				a_     			=   [layer_name]

		if len(UpperCamelCase	) > 1:
			a_     			=   [key for key in output_blocks[i] if F"""output_blocks.{i}.0""" in key]
			a_     			=   [key for key in output_blocks[i] if F"""output_blocks.{i}.1""" in key]
			a_     			=   [key for key in output_blocks[i] if F"""output_blocks.{i}.2""" in key]

			a_     			=   renew_resnet_paths(UpperCamelCase	)
			a_     			=   renew_resnet_paths(UpperCamelCase	)

			a_     			=   {"""old""": F"""output_blocks.{i}.0""", """new""": F"""up_blocks.{block_id}.resnets.{layer_in_block_id}"""}
			assign_to_checkpoint(
			    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					additional_replacements=[meta_path]     ,					config=UpperCamelCase	)

			a_     			=   [key for key in resnets if """temopral_conv""" in key]
			a_     			=   renew_temp_conv_paths(UpperCamelCase	)
			a_     			=   {
			    """old""": F"""output_blocks.{i}.0.temopral_conv""",
			    """new""": F"""up_blocks.{block_id}.temp_convs.{layer_in_block_id}""",
			}
			assign_to_checkpoint(
			    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					additional_replacements=[meta_path]     ,					config=UpperCamelCase	)

			a_     			=   {k: sorted(UpperCamelCase	) for k, v in output_block_list.items()}
			if ["conv.bias", "conv.weight"] in output_block_list.values():
				a_     			=   list(output_block_list.values()	).index(["""conv.bias""", """conv.weight"""]	)
				a_     			=   unet_state_dict[
				    F"""output_blocks.{i}.{index}.conv.weight"""
				]
				a_     			=   unet_state_dict[
				    F"""output_blocks.{i}.{index}.conv.bias"""
				]

				# Clear attentions as they have been attributed above.
				if len(UpperCamelCase	) == 2:
					a_     			=   []

			if len(UpperCamelCase	):
				a_     			=   renew_attention_paths(UpperCamelCase	)
				a_     			=   {
				    """old""": F"""output_blocks.{i}.1""",
				    """new""": F"""up_blocks.{block_id}.attentions.{layer_in_block_id}""",
				}
				assign_to_checkpoint(
				    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					additional_replacements=[meta_path]     ,					config=UpperCamelCase	)

			if len(UpperCamelCase	):
				a_     			=   renew_attention_paths(UpperCamelCase	)
				a_     			=   {
				    """old""": F"""output_blocks.{i}.2""",
				    """new""": F"""up_blocks.{block_id}.temp_attentions.{layer_in_block_id}""",
				}
				assign_to_checkpoint(
				    UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase     ,					additional_replacements=[meta_path]     ,					config=UpperCamelCase	)
		else:
			a_     			=   renew_resnet_paths(UpperCamelCase     ,					n_shave_prefix_segments=1	)
			for path in resnet_0_paths:
				a_     			=   """.""".join(["""output_blocks""", str(UpperCamelCase	), path["""old"""]]	)
				a_     			=   """.""".join(["""up_blocks""", str(UpperCamelCase	), """resnets""", str(UpperCamelCase	), path["""new"""]]	)
				a_     			=   unet_state_dict[old_path]

			a_     			=   [l for l in output_block_layers if """temopral_conv""" in l]
			for path in temopral_conv_paths:
				a_     			=   path.split("""temopral_conv."""	)[-1]
				a_     			=   """.""".join(["""output_blocks""", str(UpperCamelCase	), str(UpperCamelCase	), """temopral_conv""", pruned_path]	)
				a_     			=   """.""".join(["""up_blocks""", str(UpperCamelCase	), """temp_convs""", str(UpperCamelCase	), pruned_path]	)
				a_     			=   unet_state_dict[old_path]

	return new_checkpoint


if __name__ == "__main__":
			_A							     =       argparse.ArgumentParser()

			parser.add_argument(
			    '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.'
			)
			parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.')
			_A							     =       parser.parse_args()

			_A							     =       torch.load(args.checkpoint_path, map_location='cpu')
			_A							     =       UNetaDConditionModel()

			_A							     =       convert_ldm_unet_checkpoint(unet_checkpoint, unet.config)

			_A							     =       set(unet.state_dict().keys()) - set(converted_ckpt.keys())
			_A							     =       set(converted_ckpt.keys()) - set(unet.state_dict().keys())

			assert len(diff_a) == len(diff_a) == 0, "Converted weights don't match"

			# load state_dict
			unet.load_state_dict(converted_ckpt)

			unet.save_pretrained(args.dump_path)

			# -- finish converting the unet --



from collections import deque

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      Dict	)     ->	Tuple:



	"""simple docstring"""






	return input(UpperCamelCase	).strip().split(""" """	)

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      int     ,					UpperCamelCase		:      int	)     ->	dict[int, list[int]]:



	"""simple docstring"""






	a_     			=   {}
	for i in range(UpperCamelCase	):
		a_     			=   []

	for e in range(UpperCamelCase	):
		a_			, a_     			=   (int(UpperCamelCase	) for i in _input(F"""Edge {e + 1}: <node1> <node2> """	))
		graph[x].append(UpperCamelCase	)
	return graph

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      int     ,					UpperCamelCase		:      int	)     ->	dict[int, list[int]]:



	"""simple docstring"""






	a_     			=   {}
	for i in range(UpperCamelCase	):
		a_     			=   []

	for e in range(UpperCamelCase	):
		a_			, a_     			=   (int(UpperCamelCase	) for i in _input(F"""Edge {e + 1}: <node1> <node2> """	))
		graph[x].append(UpperCamelCase	)
		graph[y].append(UpperCamelCase	)
	return graph

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      int     ,					UpperCamelCase		:      int	)     ->	dict[int, list[tuple[int, int]]]:



	"""simple docstring"""






	a_     			=   {}
	for i in range(UpperCamelCase	):
		a_     			=   []

	for e in range(UpperCamelCase	):
		a_			, a_			, a_     			=   (int(UpperCamelCase	) for i in _input(F"""Edge {e + 1}: <node1> <node2> <weight> """	))
		graph[x].append((y, w)	)
		graph[y].append((x, w)	)
	return graph


if __name__ == "__main__":
			_A     ,				_A							     =       (int(i) for i in _input('Number of nodes and edges: '))

			_A							     =       int(
			    _input(
			        'Press 1 or 2 or 3 \n'
			        '1. Unweighted directed \n'
			        '2. Unweighted undirected \n'
			        '3. Weighted undirected \n'
			    )[0]
			)

			_A							     =       {
			    1: initialize_unweighted_directed_graph,
			    2: initialize_unweighted_undirected_graph,
			    3: initialize_weighted_undirected_graph,
			}[graph_choice](n, m)

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      Tuple     ,					UpperCamelCase		:      Tuple	)     ->	List[Any]:



	"""simple docstring"""






	a_			, a_     			=   {s}, [s]
	print(UpperCamelCase	)
	while _s:
		a_     			=   0
		for i in g[_s[-1]]:
			if i not in vis:
				_s.append(UpperCamelCase	)
				vis.add(UpperCamelCase	)
				a_     			=   1
				print(UpperCamelCase	)
				break
		if not flag:
			_s.pop()

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      Tuple     ,					UpperCamelCase		:      int	)     ->	int:



	"""simple docstring"""






	a_			, a_     			=   {s}, deque([s]	)
	print(UpperCamelCase	)
	while q:
		a_     			=   q.popleft()
		for v in g[u]:
			if v not in vis:
				vis.add(UpperCamelCase	)
				q.append(UpperCamelCase	)
				print(UpperCamelCase	)

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      int     ,					UpperCamelCase		:      Any	)     ->	Union[str, Any]:



	"""simple docstring"""






	a_			, a_			, a_     			=   {s: 0}, set(), {s: 0}
	while True:
		if len(UpperCamelCase	) == len(UpperCamelCase	) - 1:
			break
		a_     			=   10_0000
		for i in dist:
			if i not in known and dist[i] < mini:
				a_     			=   dist[i]
				a_     			=   i
		known.add(UpperCamelCase	)
		for v in g[u]:
			if v[0] not in known and dist[u] + v[1] < dist.get(v[0]     ,					10_0000	):
				a_     			=   dist[u] + v[1]
				a_     			=   u
	for i in dist:
		if i != s:
			print(dist[i]	)

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      Dict     ,					UpperCamelCase		:      int=None     ,					UpperCamelCase		:      int=None	)     ->	Union[str, Any]:



	"""simple docstring"""






	if q is None:
		a_     			=   [1]
	if ind is None:
		a_     			=   [0] * (len(UpperCamelCase	) + 1)  # SInce oth Index is ignored
		for u in g:
			for v in g[u]:
				ind[v] += 1
		a_     			=   deque()
		for i in g:
			if ind[i] == 0:
				q.append(UpperCamelCase	)
	if len(UpperCamelCase	) == 0:
		return
	a_     			=   q.popleft()
	print(UpperCamelCase	)
	for w in g[v]:
		ind[w] -= 1
		if ind[w] == 0:
			q.append(UpperCamelCase	)
	topo(UpperCamelCase     ,					UpperCamelCase     ,					UpperCamelCase	)

def 			__SCREAMING_SNAKE_CASE		(		)     ->	List[Any]:



	"""simple docstring"""






	a_     			=   input().strip()
	a_     			=   []
	for _ in range(UpperCamelCase	):
		a.append(map(UpperCamelCase     ,					input().strip().split()	)	)
	return a, n

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      List[Any]	)     ->	List[str]:



	"""simple docstring"""






	((a_)			, (a_))     			=   a_and_n
	a_     			=   list(UpperCamelCase	)
	a_     			=   [[0] * n for i in range(UpperCamelCase	)]
	for k in range(UpperCamelCase	):
		for i in range(UpperCamelCase	):
			for j in range(UpperCamelCase	):
				if dist[i][j] > dist[i][k] + dist[k][j]:
					a_     			=   dist[i][k] + dist[k][j]
					a_     			=   k
	print(UpperCamelCase	)

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      Dict     ,					UpperCamelCase		:      List[Any]	)     ->	str:



	"""simple docstring"""






	a_			, a_			, a_     			=   {s: 0}, set(), {s: 0}
	while True:
		if len(UpperCamelCase	) == len(UpperCamelCase	) - 1:
			break
		a_     			=   10_0000
		for i in dist:
			if i not in known and dist[i] < mini:
				a_     			=   dist[i]
				a_     			=   i
		known.add(UpperCamelCase	)
		for v in g[u]:
			if v[0] not in known and v[1] < dist.get(v[0]     ,					10_0000	):
				a_     			=   v[1]
				a_     			=   u
	return dist

def 			__SCREAMING_SNAKE_CASE		(		)     ->	int:



	"""simple docstring"""






	a_			, a_     			=   map(UpperCamelCase     ,					input().split(""" """	)	)
	a_     			=   []
	for _ in range(UpperCamelCase	):
		edges.append(map(UpperCamelCase     ,					input().split(""" """	)	)	)
	return edges, n

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      List[str]	)     ->	List[str]:



	"""simple docstring"""






	((a_)			, (a_))     			=   e_and_n
	e.sort(reverse=UpperCamelCase     ,					key=lambda UpperCamelCase	: x[2]	)
	a_     			=   [{i} for i in range(1     ,					n + 1	)]
	while True:
		if len(UpperCamelCase	) == 1:
			break
		print(UpperCamelCase	)
		a_     			=   e.pop()
		for i in range(len(UpperCamelCase	)	):
			if x[0] in s[i]:
				break
		for j in range(len(UpperCamelCase	)	):
			if x[1] in s[j]:
				if i == j:
					break
				s[j].update(s[i]	)
				s.pop(UpperCamelCase	)
				break

def 			__SCREAMING_SNAKE_CASE		(		UpperCamelCase		:      str	)     ->	Optional[Any]:



	"""simple docstring"""






	a_     			=   []
	for node in graph:
		if not graph[node]:
			isolated.append(UpperCamelCase	)
	return isolated