


from typing import Callable, List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModel, CLIPTokenizer

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin, TransformeraDModel, VQModel
from ...schedulers import VQDiffusionScheduler
from ...utils import logging
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


snake_case__			 =						logging.get_logger(__name__)  # pylint: disable=invalid-name


class 					lowerCAmelCase_ (       _a			,_a):




						@register_to_config
						def __init__(	self						:   Optional[Any]   ,     __A						:   bool   ,     __A						:   Optional[int] = None   ,     __A						:   Optional[int] = None						)      ->Any:






									"""simple docstring"""






									super().__init__()

									a__ :Tuple						  =    learnable

									if self.learnable:
												assert hidden_size is not None, "learnable=True requires `hidden_size` to be set"
												assert length is not None, "learnable=True requires `length` to be set"

												a__ :int						  =    torch.zeros(__A   ,     __A						)
									else:
												a__ :Dict						  =    None

									a__ :List[Any]						  =    torch.nn.Parameter(__A						)






class 					lowerCAmelCase_ (       _a):
						lowerCamelCase_         =     42
						lowerCamelCase_         =     42
						lowerCamelCase_         =     42
						lowerCamelCase_         =     42
						lowerCamelCase_         =     42
						lowerCamelCase_         =     42




						def __init__(	self						:   Optional[int]   ,     __A						:   VQModel   ,     __A						:   CLIPTextModel   ,     __A						:   CLIPTokenizer   ,     __A						:   TransformeraDModel   ,     __A						:   VQDiffusionScheduler   ,     __A						:   LearnedClassifierFreeSamplingEmbeddings   ,     )      ->List[str]:






									"""simple docstring"""






									super().__init__()

									self.register_modules(
									    vqvae=__A   ,     transformer=__A   ,     text_encoder=__A   ,     tokenizer=__A   ,     scheduler=__A   ,     learned_classifier_free_sampling_embeddings=__A   ,     )




						def  _snake_case					(	self						:   str   ,     __A						:   Optional[Any]   ,     __A						:   List[str]   ,     __A						:   List[str]						)      ->List[Any]:






									"""simple docstring"""






									a__ :str						  =    len(__A						) if isinstance(__A   ,     __A						) else 1

									# get prompt text embeddings
									a__ :Optional[Any]						  =    self.tokenizer(
									    __A   ,     padding="max_length"   ,     max_length=self.tokenizer.model_max_length   ,     return_tensors="pt"   ,     )
									a__ :int						  =    text_inputs.input_ids

									if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
												a__ :Dict						  =    self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]						)
												logger.warning(
												    "The following part of your input was truncated because CLIP can only handle sequences up to"
												    F''' {self.tokenizer.model_max_length} tokens: {removed_text}'''						)
												a__ :List[str]						  =    text_input_ids[:, : self.tokenizer.model_max_length]
									a__ :Optional[int]						  =    self.text_encoder(text_input_ids.to(self.device						)						)[0]

									# NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion.
									# While CLIP does normalize the pooled output of the text transformer when combining
									# the image and text embeddings, CLIP does not directly normalize the last hidden state.
									#
									# CLIP normalizing the pooled output.
									# https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053
									a__ :Optional[int]						  =    prompt_embeds / prompt_embeds.norm(dim=-1   ,     keepdim=__A						)

									# duplicate text embeddings for each generation per prompt
									a__ :Optional[int]						  =    prompt_embeds.repeat_interleave(__A   ,     dim=0						)

									if do_classifier_free_guidance:
												if self.learned_classifier_free_sampling_embeddings.learnable:
															a__ :Any						  =    self.learned_classifier_free_sampling_embeddings.embeddings
															a__ :int						  =    negative_prompt_embeds.unsqueeze(0						).repeat(__A   ,     1   ,     1						)
												else:
															a__ :Tuple						  =    [""] * batch_size

															a__ :Dict						  =    text_input_ids.shape[-1]
															a__ :str						  =    self.tokenizer(
															    __A   ,     padding="max_length"   ,     max_length=__A   ,     truncation=__A   ,     return_tensors="pt"   ,     )
															a__ :Tuple						  =    self.text_encoder(uncond_input.input_ids.to(self.device						)						)[0]
															# See comment for normalizing text embeddings
															a__ :Dict						  =    negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1   ,     keepdim=__A						)

												# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
												a__ :List[str]						  =    negative_prompt_embeds.shape[1]
												a__ :Optional[Any]						  =    negative_prompt_embeds.repeat(1   ,     __A   ,     1						)
												a__ :str						  =    negative_prompt_embeds.view(batch_size * num_images_per_prompt   ,     __A   ,     -1						)

												# For classifier free guidance, we need to do two forward passes.
												# Here we concatenate the unconditional and text embeddings into a single batch
												# to avoid doing two forward passes
												a__ :Dict						  =    torch.cat([negative_prompt_embeds, prompt_embeds]						)

									return prompt_embeds




						@torch.no_grad()
						def __call__(	self						:   Dict   ,     __A						:   Union[str, List[str]]   ,     __A						:   int = 100   ,     __A						:   float = 5.0   ,     __A						:   float = 1.0   ,     __A						:   int = 1   ,     __A						:   Optional[Union[torch.Generator, List[torch.Generator]]] = None   ,     __A						:   Optional[torch.FloatTensor] = None   ,     __A						:   Optional[str] = "pil"   ,     __A						:   bool = True   ,     __A						:   Optional[Callable[[int, int, torch.FloatTensor], None]] = None   ,     __A						:   int = 1   ,     )      ->Union[ImagePipelineOutput, Tuple]:






									"""simple docstring"""






									if isinstance(__A   ,     __A						):
												a__ :List[Any]						  =    1
									elif isinstance(__A   ,     __A						):
												a__ :List[Any]						  =    len(__A						)
									else:
												raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(__A						)}'''						)

									a__ :Optional[int]						  =    batch_size * num_images_per_prompt

									a__ :List[Any]						  =    guidance_scale > 1.0

									a__ :Tuple						  =    self._encode_prompt(__A   ,     __A   ,     __A						)

									if (callback_steps is None) or (
									    callback_steps is not None and (not isinstance(__A   ,     __A						) or callback_steps <= 0)
									):
												raise ValueError(
												    F'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
												    F''' {type(__A						)}.'''						)

									# get the initial completely masked latents unless the user supplied it

									a__ :str						  =    (batch_size, self.transformer.num_latent_pixels)
									if latents is None:
												a__ :Dict						  =    self.transformer.num_vector_embeds - 1
												a__ :Tuple						  =    torch.full(__A   ,     __A						).to(self.device						)
									else:
												if latents.shape != latents_shape:
															raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}'''						)
												if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any():
															raise ValueError(
															    "Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,"
															    F''' {self.transformer.num_vector_embeds - 1} (inclusive).'''						)
												a__ :Dict						  =    latents.to(self.device						)

									# set timesteps
									self.scheduler.set_timesteps(__A   ,     device=self.device						)

									a__ :Any						  =    self.scheduler.timesteps.to(self.device						)

									a__ :int						  =    latents

									for i, t in enumerate(self.progress_bar(__A						)						):
												# expand the sample if we are doing classifier free guidance
												a__ :int						  =    torch.cat([sample] * 2						) if do_classifier_free_guidance else sample

												# predict the un-noised image
												# model_output == `log_p_x_0`
												a__ :int						  =    self.transformer(__A   ,     encoder_hidden_states=__A   ,     timestep=__A						).sample

												if do_classifier_free_guidance:
															a__  ,  a__ :Any						  =    model_output.chunk(2						)
															a__ :Tuple						  =    model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
															model_output -= torch.logsumexp(__A   ,     dim=1   ,     keepdim=__A						)

												a__ :Any						  =    self.truncate(__A   ,     __A						)

												# remove `log(0)`'s (`-inf`s)
												a__ :str						  =    model_output.clamp(-70						)

												# compute the previous noisy sample x_t -> x_t-1
												a__ :Tuple						  =    self.scheduler.step(__A   ,     timestep=__A   ,     sample=__A   ,     generator=__A						).prev_sample

												# call the callback, if provided
												if callback is not None and i % callback_steps == 0:
															callback(__A   ,     __A   ,     __A						)

									a__ :Tuple						  =    self.vqvae.config.vq_embed_dim
									a__ :int						  =    (batch_size, self.transformer.height, self.transformer.width, embedding_channels)
									a__ :int						  =    self.vqvae.quantize.get_codebook_entry(__A   ,     shape=__A						)
									a__ :Tuple						  =    self.vqvae.decode(__A   ,     force_not_quantize=__A						).sample

									a__ :int						  =    (image / 2 + 0.5).clamp(0   ,     1						)
									a__ :int						  =    image.cpu().permute(0   ,     2   ,     3   ,     1						).numpy()

									if output_type == "pil":
												a__ :Any						  =    self.numpy_to_pil(__A						)

									if not return_dict:
												return (image,)

									return ImagePipelineOutput(images=__A						)






						def  _snake_case					(	self						:   Optional[Any]   ,     __A						:   torch.FloatTensor   ,     __A						:   float						)      ->torch.FloatTensor:






									"""simple docstring"""






									a__  ,  a__ :str						  =    torch.sort(__A   ,     1   ,     descending=__A						)
									a__ :List[Any]						  =    torch.exp(__A						)
									a__ :Union[str, Any]						  =    sorted_p_x_0.cumsum(dim=1						) < truncation_rate

									# Ensure that at least the largest probability is not zeroed out
									a__ :Dict						  =    torch.full_like(keep_mask[:, 0:1, :]   ,     __A						)
									a__ :Union[str, Any]						  =    torch.cat((all_true, keep_mask)   ,     dim=1						)
									a__ :Optional[int]						  =    keep_mask[:, :-1, :]

									a__ :Tuple						  =    keep_mask.gather(1   ,     indices.argsort(1						)						)

									a__ :List[str]						  =    log_p_x_0.clone()

									a__ :Any						  =    -torch.inf  # -inf = log(0)

									return rv






import sys
from collections import defaultdict


class 					lowerCAmelCase_ :




						def __init__(	self						:   Optional[int]						)      ->Any:






									"""simple docstring"""






									a__ :Optional[Any]						  =    []




						def  _snake_case					(	self						:   Optional[Any]   ,     __A						:   List[Any]						)      ->List[str]:






									"""simple docstring"""






									return self.node_position[vertex]




						def  _snake_case					(	self						:   Optional[Any]   ,     __A						:   str   ,     __A						:   Any						)      ->Dict:






									"""simple docstring"""






									a__ :Dict						  =    pos




						def  _snake_case					(	self						:   str   ,     __A						:   Union[str, Any]   ,     __A						:   Union[str, Any]   ,     __A						:   Optional[Any]   ,     __A						:   Optional[int]						)      ->List[Any]:






									"""simple docstring"""






									if start > size // 2 - 1:
												return
									else:
												if 2 * start + 2 >= size:
															a__ :str						  =    2 * start + 1
												else:
															if heap[2 * start + 1] < heap[2 * start + 2]:
																		a__ :Optional[int]						  =    2 * start + 1
															else:
																		a__ :List[Any]						  =    2 * start + 2
												if heap[smallest_child] < heap[start]:
															a__  ,  a__ :Optional[Any]						  =    heap[smallest_child], positions[smallest_child]
															a__  ,  a__ :int						  =    (
															    heap[start],
															    positions[start],
															)
															a__  ,  a__ :List[Any]						  =    temp, tempa

															a__ :Any						  =    self.get_position(positions[smallest_child]						)
															self.set_position(
															    positions[smallest_child]   ,     self.get_position(positions[start]						)						)
															self.set_position(positions[start]   ,     __A						)

															self.top_to_bottom(__A   ,     __A   ,     __A   ,     __A						)




						def  _snake_case					(	self						:   List[str]   ,     __A						:   Any   ,     __A						:   List[str]   ,     __A						:   Any   ,     __A						:   str						)      ->Optional[Any]:






									"""simple docstring"""






									a__ :Optional[Any]						  =    position[index]

									while index != 0:
												a__ :str						  =    int((index - 2) / 2						) if index % 2 == 0 else int((index - 1) / 2						)

												if val < heap[parent]:
															a__ :int						  =    heap[parent]
															a__ :Optional[Any]						  =    position[parent]
															self.set_position(position[parent]   ,     __A						)
												else:
															a__ :List[Any]						  =    val
															a__ :List[Any]						  =    temp
															self.set_position(__A   ,     __A						)
															break
												a__ :Union[str, Any]						  =    parent
									else:
												a__ :int						  =    val
												a__ :Dict						  =    temp
												self.set_position(__A   ,     0						)




						def  _snake_case					(	self						:   Tuple   ,     __A						:   int   ,     __A						:   int						)      ->Union[str, Any]:






									"""simple docstring"""






									a__ :Tuple						  =    len(__A						) // 2 - 1
									for i in range(__A   ,     -1   ,     -1						):
												self.top_to_bottom(__A   ,     __A   ,     len(__A						)   ,     __A						)






						def  _snake_case					(	self						:   List[Any]   ,     __A						:   List[Any]   ,     __A						:   int						)      ->Optional[Any]:






									"""simple docstring"""






									a__ :Any						  =    positions[0]
									a__ :str						  =    sys.maxsize
									self.top_to_bottom(__A   ,     0   ,     len(__A						)   ,     __A						)
									return temp






def 				lowerCamelCase__	(      a	:   Any				)    ->	Union[str, Any]:





			"""simple docstring"""
			a__ :Tuple						  =    Heap()

			a__ :List[Any]						  =    [0] * len(a				)
			a__ :str						  =    [-1] * len(a				)  # Neighboring Tree Vertex of selected vertex
			# Minimum Distance of explored vertex with neighboring vertex of partial tree
			# formed in graph
			a__ :Any						  =    []  # Heap of Distance of vertices from their neighboring vertex
			a__ :int						  =    []

			for vertex in range(len(a				)				):
						distance_tv.append(sys.maxsize				)
						positions.append(a				)
						heap.node_position.append(a				)

			a__ :Tuple						  =    []
			a__ :Any						  =    1
			a__ :int						  =    sys.maxsize
			for neighbor, distance in adjacency_list[0]:
						a__ :int						  =    0
						a__ :List[str]						  =    distance
			heap.heapify(a	,  a				)

			for _ in range(1	,  len(a				)				):
						a__ :Dict						  =    heap.delete_minimum(a	,  a				)
						if visited[vertex] == 0:
									tree_edges.append((nbr_tv[vertex], vertex)				)
									a__ :Optional[int]						  =    1
									for neighbor, distance in adjacency_list[vertex]:
												if (
												    visited[neighbor] == 0
												    and distance < distance_tv[heap.get_position(a				)]
												):
															a__ :List[str]						  =    distance
															heap.bottom_to_top(
															    a	,  heap.get_position(a				)	,  a	,  a				)
															a__ :str						  =    vertex
			return tree_edges


if __name__ == "__main__":  # pragma: no cover
		# < --------- Prims Algorithm --------- >
		snake_case__			 =						int(input('''Enter number of edges: ''').strip())
		snake_case__			 =						defaultdict(list)
		for _ in range(edges_number):
				snake_case__			 =						[int(x) for x in input().strip().split()]
				adjacency_list[edge[0]].append([edge[1], edge[2]])
				adjacency_list[edge[1]].append([edge[0], edge[2]])
		print(prisms_algorithm(adjacency_list))


