


'''simple docstring'''







import sys
from collections import defaultdict







class A__       :






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




             '''simple docstring'''
             _a    : List[Any]     					=[]






      def __UpperCAmelCase       ( self			:Optional[Any]     ,						SCREAMING_SNAKE_CASE			:List[Any]	)       ->					Union[str, Any]:




             '''simple docstring'''
             return self.node_position[vertex]






      def __UpperCAmelCase       ( self			:Union[str, Any]     ,						SCREAMING_SNAKE_CASE			:Optional[Any]     ,						SCREAMING_SNAKE_CASE			:str	)       ->					str:




             '''simple docstring'''
             _a    : Dict     					=pos






      def __UpperCAmelCase       ( self			:Any     ,						SCREAMING_SNAKE_CASE			:Any     ,						SCREAMING_SNAKE_CASE			:Any     ,						SCREAMING_SNAKE_CASE			:List[Any]     ,						SCREAMING_SNAKE_CASE			:Optional[int]	)       ->					Optional[int]:




             '''simple docstring'''
             if start > size // 2 - 1:
                    return
             else:
                    if 2 * start + 2 >= size:
                           _a    : Union[str, Any]     					=2 * start + 1
                    else:
                           if heap[2 * start + 1] < heap[2 * start + 2]:
                                  _a    : List[Any]     					=2 * start + 1
                           else:
                                  _a    : List[str]     					=2 * start + 2
                    if heap[smallest_child] < heap[start]:
                           _a					,    _a    : Tuple     					=heap[smallest_child], positions[smallest_child]
                           _a					,    _a    : Optional[Any]     					=(
                               heap[start],
                               positions[start],
                           )
                           _a					,    _a    : str     					=temp, tempa

                           _a    : int     					=self.get_position(positions[smallest_child]	)
                           self.set_position(
                               positions[smallest_child]     ,						self.get_position(positions[start]	)	)
                           self.set_position(positions[start]     ,						SCREAMING_SNAKE_CASE	)

                           self.top_to_bottom(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE	)






      def __UpperCAmelCase       ( self			:List[Any]     ,						SCREAMING_SNAKE_CASE			:List[Any]     ,						SCREAMING_SNAKE_CASE			:Union[str, Any]     ,						SCREAMING_SNAKE_CASE			:Optional[Any]     ,						SCREAMING_SNAKE_CASE			:int	)       ->					Dict:




             '''simple docstring'''
             _a    : Optional[int]     					=position[index]

             while index != 0:
                    _a    : Optional[int]     					=int((index - 2) / 2	) if index % 2 == 0 else int((index - 1) / 2	)

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






      def __UpperCAmelCase       ( self			:Optional[Any]     ,						SCREAMING_SNAKE_CASE			:Any     ,						SCREAMING_SNAKE_CASE			:List[Any]	)       ->					List[str]:




             '''simple docstring'''
             _a    : Dict     					=len(SCREAMING_SNAKE_CASE	) // 2 - 1
             for i in range(SCREAMING_SNAKE_CASE     ,						-1     ,						-1	):
                    self.top_to_bottom(SCREAMING_SNAKE_CASE     ,						SCREAMING_SNAKE_CASE     ,						len(SCREAMING_SNAKE_CASE	)     ,						SCREAMING_SNAKE_CASE	)






      def __UpperCAmelCase       ( self			:str     ,						SCREAMING_SNAKE_CASE			:str     ,						SCREAMING_SNAKE_CASE			:Optional[int]	)       ->					Optional[Any]:




             '''simple docstring'''
             _a    : str     					=positions[0]
             _a    : List[Any]     					=sys.maxsize
             self.top_to_bottom(SCREAMING_SNAKE_CASE     ,						0     ,						len(SCREAMING_SNAKE_CASE	)     ,						SCREAMING_SNAKE_CASE	)
             return temp


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	Union[str, Any]  )  ->			List[str]:
       _a    : str     					=Heap()

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

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

       _a    : Optional[int]     					=[]
       _a    : Optional[Any]     					=1
       _a    : List[str]     					=sys.maxsize
       for neighbor, distance in adjacency_list[0]:
              _a    : List[Any]     					=0
              _a    : Optional[int]     					=distance
       heap.heapify(_UpperCAmelCase    ,_UpperCAmelCase  )

       for _ in range(1    ,len(_UpperCAmelCase  )  ):
              _a    : Tuple     					=heap.delete_minimum(_UpperCAmelCase    ,_UpperCAmelCase  )
              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(_UpperCAmelCase  )]
                            ):
                                   _a    : Union[str, Any]     					=distance
                                   heap.bottom_to_top(
                                       _UpperCAmelCase    ,heap.get_position(_UpperCAmelCase  )    ,_UpperCAmelCase    ,_UpperCAmelCase  )
                                   _a    : List[str]     					=vertex
       return tree_edges


if __name__ == "__main__":  # pragma: no cover
   # < --------- Prims Algorithm --------- >
   A__:    List[str]					    =       int(input('''Enter number of edges: ''').strip())
   A__:    List[Any]					    =       defaultdict(list)
   for _ in range(edges_number):
      A__:    Union[str, Any]					    =       [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))






'''simple docstring'''







import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
   import bitsandbytes as bnb
   import torch
   import torch.nn as nn

   from ..pytorch_utils import ConvaD

if is_accelerate_available():
   from accelerate import init_empty_weights
   from accelerate.utils import find_tied_parameters

A__:    str					    =       logging.get_logger(__name__)


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	List[Any]    ,_UpperCAmelCase	:	List[str]    ,_UpperCAmelCase	:	int    ,_UpperCAmelCase	:	int=None    ,_UpperCAmelCase	:	Optional[Any]=None  )  ->			Optional[Any]:
       # Recurse if needed
       if "." in tensor_name:
              _a    : Union[str, Any]     					=tensor_name.split("""."""  )
              for split in splits[:-1]:
                     _a    : Optional[Any]     					=getattr(_UpperCAmelCase    ,_UpperCAmelCase  )
                     if new_module is None:
                            raise ValueError(F"{module} has no attribute {split}."  )
                     _a    : Optional[int]     					=new_module
              _a    : Optional[int]     					=splits[-1]

       if tensor_name not in module._parameters and tensor_name not in module._buffers:
              raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}."  )
       _a    : Optional[Any]     					=tensor_name in module._buffers
       _a    : str     					=getattr(_UpperCAmelCase    ,_UpperCAmelCase  )

       if old_value.device == torch.device("""meta"""  ) and device not in ["meta", torch.device("""meta"""  )] and value is None:
              raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}."  )

       _a    : int     					=False
       _a    : Tuple     					=False
       if is_buffer or not is_bitsandbytes_available():
              _a    : str     					=False
              _a    : Optional[Any]     					=False
       else:
              _a    : int     					=hasattr(bnb.nn    ,"""Params4bit"""  ) and isinstance(module._parameters[tensor_name]    ,bnb.nn.Paramsabit  )
              _a    : int     					=isinstance(module._parameters[tensor_name]    ,bnb.nn.IntaParams  )

       if is_abit or is_abit:
              _a    : Any     					=module._parameters[tensor_name]
              if param.device.type != "cuda":
                     if value is None:
                            _a    : int     					=old_value.to(_UpperCAmelCase  )
                     elif isinstance(_UpperCAmelCase    ,torch.Tensor  ):
                            _a    : str     					=value.to("""cpu"""  )
                            if value.dtype == torch.inta:
                                   _a    : int     					=version.parse(importlib.metadata.version("""bitsandbytes"""  )  ) > version.parse(
                                       """0.37.2"""  )
                                   if not is_abit_serializable:
                                          raise ValueError(
                                              """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """
                                              """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."""  )
                     else:
                            _a    : Dict     					=torch.tensor(_UpperCAmelCase    ,device="""cpu"""  )

                     # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
                     # Since weights are saved in the correct "orientation", we skip transposing when loading.
                     if issubclass(module.source_cls    ,_UpperCAmelCase  ) and fpaa_statistics is None:
                            _a    : int     					=new_value.T

                     _a    : Any     					=old_value.__dict__
                     if is_abit:
                            _a    : Any     					=bnb.nn.IntaParams(_UpperCAmelCase    ,requires_grad=_UpperCAmelCase    ,**_UpperCAmelCase  ).to(_UpperCAmelCase  )
                     elif is_abit:
                            _a    : Union[str, Any]     					=bnb.nn.Paramsabit(_UpperCAmelCase    ,requires_grad=_UpperCAmelCase    ,**_UpperCAmelCase  ).to(_UpperCAmelCase  )

                     _a    : List[Any]     					=new_value
                     if fpaa_statistics is not None:
                            setattr(module.weight    ,"""SCB"""    ,fpaa_statistics.to(_UpperCAmelCase  )  )

       else:
              if value is None:
                     _a    : str     					=old_value.to(_UpperCAmelCase  )
              elif isinstance(_UpperCAmelCase    ,torch.Tensor  ):
                     _a    : Any     					=value.to(_UpperCAmelCase  )
              else:
                     _a    : str     					=torch.tensor(_UpperCAmelCase    ,device=_UpperCAmelCase  )

              if is_buffer:
                     _a    : Optional[int]     					=new_value
              else:
                     _a    : Optional[Any]     					=nn.Parameter(_UpperCAmelCase    ,requires_grad=old_value.requires_grad  )
                     _a    : Tuple     					=new_value


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	Tuple    ,_UpperCAmelCase	:	Union[str, Any]=None    ,_UpperCAmelCase	:	List[Any]=None    ,_UpperCAmelCase	:	str=None    ,_UpperCAmelCase	:	Union[str, Any]=False  )  ->			Dict:
       for name, module in model.named_children():
              if current_key_name is None:
                     _a    : Optional[int]     					=[]
              current_key_name.append(_UpperCAmelCase  )

              if (isinstance(_UpperCAmelCase    ,nn.Linear  ) or isinstance(_UpperCAmelCase    ,_UpperCAmelCase  )) and name not in modules_to_not_convert:
                     # Check if the current key is not in the `modules_to_not_convert`
                     if not any(key in """.""".join(_UpperCAmelCase  ) for key in modules_to_not_convert  ):
                            with init_empty_weights():
                                   if isinstance(_UpperCAmelCase    ,_UpperCAmelCase  ):
                                          _a					,    _a    : int     					=module.weight.shape
                                   else:
                                          _a    : List[str]     					=module.in_features
                                          _a    : Tuple     					=module.out_features

                                   if quantization_config.quantization_method() == "llm_int8":
                                          _a    : Optional[Any]     					=bnb.nn.LinearabitLt(
                                              _UpperCAmelCase    ,_UpperCAmelCase    ,module.bias is not None    ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight    ,threshold=quantization_config.llm_inta_threshold    ,)
                                          _a    : Optional[Any]     					=True
                                   else:
                                          if (
                                              quantization_config.llm_inta_skip_modules is not None
                                              and name in quantization_config.llm_inta_skip_modules
                                          ):
                                                 pass
                                          else:
                                                 _a    : Dict     					=bnb.nn.Linearabit(
                                                     _UpperCAmelCase    ,_UpperCAmelCase    ,module.bias is not None    ,quantization_config.bnb_abit_compute_dtype    ,compress_statistics=quantization_config.bnb_abit_use_double_quant    ,quant_type=quantization_config.bnb_abit_quant_type    ,)
                                                 _a    : List[Any]     					=True
                    # Store the module class in case we need to transpose the weight later
                                   _a    : int     					=type(_UpperCAmelCase  )
                                   # Force requires grad to False to avoid unexpected errors
                                   model._modules[name].requires_grad_(_UpperCAmelCase  )
              if len(list(module.children()  )  ) > 0:
                     _a					,    _a    : List[Any]     					=_replace_with_bnb_linear(
                         _UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase    ,has_been_replaced=_UpperCAmelCase    ,)
              # Remove the last key for recursion
              current_key_name.pop(-1  )
       return model, has_been_replaced


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	Tuple    ,_UpperCAmelCase	:	int=None    ,_UpperCAmelCase	:	Union[str, Any]=None    ,_UpperCAmelCase	:	Any=None  )  ->			Tuple:
       _a    : Dict     					=["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert
       _a					,    _a    : List[Any]     					=_replace_with_bnb_linear(
           _UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase    ,_UpperCAmelCase  )

       if not has_been_replaced:
              logger.warning(
                  """You are loading your model in 8bit or 4bit but no linear modules were found in your model."""
                  """ Please double check your model architecture, or submit an issue on github if you think this is"""
                  """ a bug."""  )

       return model


def 	SCREAMING_SNAKE_CASE_					(  *_UpperCAmelCase	:	Any    ,**_UpperCAmelCase	:	Any  )  ->			str:
       warnings.warn(
           """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead"""    ,_UpperCAmelCase    ,)
       return replace_with_bnb_linear(*_UpperCAmelCase    ,**_UpperCAmelCase  )


def 	SCREAMING_SNAKE_CASE_					(  *_UpperCAmelCase	:	str    ,**_UpperCAmelCase	:	Optional[int]  )  ->			Optional[int]:
       warnings.warn(
           """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead"""    ,_UpperCAmelCase    ,)
       return set_module_quantized_tensor_to_device(*_UpperCAmelCase    ,**_UpperCAmelCase  )


def 	SCREAMING_SNAKE_CASE_					(  _UpperCAmelCase	:	int  )  ->			Union[str, Any]:
       _a    : Any     					=deepcopy(_UpperCAmelCase  )  # this has 0 cost since it is done inside `init_empty_weights` context manager`
       tied_model.tie_weights()

       _a    : List[Any]     					=find_tied_parameters(_UpperCAmelCase  )
       # For compatibility with Accelerate < 0.18
       if isinstance(_UpperCAmelCase    ,_UpperCAmelCase  ):
              _a    : str     					=sum(list(tied_params.values()  )    ,[]  ) + list(tied_params.keys()  )
       else:
              _a    : Optional[int]     					=sum(_UpperCAmelCase    ,[]  )
       _a    : List[Any]     					=len(_UpperCAmelCase  ) > 0

       # Check if it is a base model
       _a    : Tuple     					=not hasattr(_UpperCAmelCase    ,model.base_model_prefix  )

       # Ignore this for base models (BertModel, GPT2Model, etc.)
       if (not has_tied_params) and is_base_model:
              return []

       # otherwise they have an attached head
       _a    : List[Any]     					=list(model.named_children()  )
       _a    : Dict     					=[list_modules[-1][0]]

       # add last module together with tied weights
       _a    : List[str]     					=set(_UpperCAmelCase  ) - set(_UpperCAmelCase  )
       _a    : str     					=list(set(_UpperCAmelCase  )  ) + list(_UpperCAmelCase  )

       # remove ".weight" from the keys
       _a    : List[Any]     					=[""".weight""", """.bias"""]
       _a    : Any     					=[]
       for name in list_untouched:
              for name_to_remove in names_to_remove:
                     if name_to_remove in name:
                            _a    : Any     					=name.replace(_UpperCAmelCase    ,""""""  )
              filtered_module_names.append(_UpperCAmelCase  )

       return filtered_module_names


