

"""simple docstring"""


import os
import sys
import tempfile

import torch

from .state import AcceleratorState
from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment




def        _lowercase    (			__lowerCAmelCase     ,    __lowerCAmelCase=()     ,    __lowerCAmelCase=None     ,    __lowerCAmelCase="no"     ,    __lowerCAmelCase="29500"							)				-> str:
      SCREAMING_SNAKE_CASE__      :					int											=		False
      SCREAMING_SNAKE_CASE__      :					List[Any]											=		False
      if any(key.startswith("""KAGGLE"""							) for key in os.environ.keys()							):
            SCREAMING_SNAKE_CASE__      :					List[Any]											=		True
      elif "IPython" in sys.modules:
            SCREAMING_SNAKE_CASE__      :					Dict											=		"""google.colab""" in str(sys.modules["""IPython"""].get_ipython()							)

      try:
            SCREAMING_SNAKE_CASE__      :					int											=		PrecisionType(mixed_precision.lower()							)
      except ValueError:
            raise ValueError(
                F'''Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.'''							)

      if (in_colab or in_kaggle) and (os.environ.get("""TPU_NAME"""     ,    _UpperCamelCase							) is not None):
            # TPU launch
            import torch_xla.distributed.xla_multiprocessing as xmp

            if len(AcceleratorState._shared_state							) > 0:
                  raise ValueError(
                      """To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside """
                      """your training function. Restart your notebook and make sure no cells initializes an """
                      """`Accelerator`."""							)
            if num_processes is None:
                  SCREAMING_SNAKE_CASE__      :					Dict											=		8

            SCREAMING_SNAKE_CASE__      :					Any											=		PrepareForLaunch(_UpperCamelCase     ,    distributed_type="""TPU"""							)
            print(F'''Launching a training on {num_processes} TPU cores.'''							)
            xmp.spawn(_UpperCamelCase     ,    args=_UpperCamelCase     ,    nprocs=_UpperCamelCase     ,    start_method="""fork"""							)
      elif in_colab:
            # No need for a distributed launch otherwise as it's either CPU or one GPU.
            if torch.cuda.is_available():
                  print("""Launching training on one GPU."""							)
            else:
                  print("""Launching training on one CPU."""							)
            function(*_UpperCamelCase							)
      else:
            if num_processes is None:
                  raise ValueError(
                      """You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call."""							)

            if num_processes > 1:
                  # Multi-GPU launch
                  from torch.multiprocessing import start_processes
                  from torch.multiprocessing.spawn import ProcessRaisedException

                  if len(AcceleratorState._shared_state							) > 0:
                        raise ValueError(
                            """To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized """
                            """inside your training function. Restart your notebook and make sure no cells initializes an """
                            """`Accelerator`."""							)

                  if torch.cuda.is_initialized():
                        raise ValueError(
                            """To launch a multi-GPU training from your notebook, you need to avoid running any instruction """
                            """using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA """
                            """function."""							)

                  # torch.distributed will expect a few environment variable to be here. We set the ones common to each
                  # process here (the other ones will be set be the launcher).
                  with patch_environment(
                      world_size=_UpperCamelCase     ,    master_addr="""127.0.01"""     ,    master_port=_UpperCamelCase     ,    mixed_precision=_UpperCamelCase							):
                        SCREAMING_SNAKE_CASE__      :					str											=		PrepareForLaunch(_UpperCamelCase     ,    distributed_type="""MULTI_GPU"""							)
                        print(F'''Launching training on {num_processes} GPUs.'''							)
                        try:
                              start_processes(_UpperCamelCase     ,    args=_UpperCamelCase     ,    nprocs=_UpperCamelCase     ,    start_method="""fork"""							)
                        except ProcessRaisedException as e:
                              if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
                                    raise RuntimeError(
                                        """CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. """
                                        """This likely stems from an outside import causing issues once the `notebook_launcher()` is called. """
                                        """Please review your imports and test them when running the `notebook_launcher()` to identify """
                                        """which one is problematic."""							) from e

            else:
                  # No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
                  if is_mps_available():
                        SCREAMING_SNAKE_CASE__      :					Optional[Any]											=		"""1"""
                        print("""Launching training on MPS."""							)
                  elif torch.cuda.is_available():
                        print("""Launching training on one GPU."""							)
                  else:
                        print("""Launching training on CPU."""							)
                  function(*_UpperCamelCase							)




def        _lowercase    (			__lowerCAmelCase     ,    __lowerCAmelCase=()     ,    __lowerCAmelCase=2							)				-> Dict:
      from torch.multiprocessing import start_processes

      with tempfile.NamedTemporaryFile() as tmp_file:
            # torch.distributed will expect a few environment variable to be here. We set the ones common to each
            # process here (the other ones will be set be the launcher).
            with patch_environment(
                world_size=_UpperCamelCase     ,    master_addr="""127.0.01"""     ,    master_port="""29500"""     ,    accelerate_mixed_precision="""no"""     ,    accelerate_debug_rdv_file=tmp_file.name     ,    accelerate_use_cpu="""yes"""     ,    ):
                  SCREAMING_SNAKE_CASE__      :					str											=		PrepareForLaunch(_UpperCamelCase     ,    debug=_UpperCamelCase							)
                  start_processes(_UpperCamelCase     ,    args=_UpperCamelCase     ,    nprocs=_UpperCamelCase     ,    start_method="""fork"""							)








"""simple docstring"""


import sys
from collections import defaultdict
class   _UpperCamelCase  :
							'''simple docstring'''







							def __init__(     self	):
										__lowerCAmelCase				    =			[]

							def 			snake_case				(     self    ,   __a	):
										return self.node_position[vertex]

							def 			snake_case				(     self    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			pos

							def 			snake_case				(     self    ,   __a    ,   __a    ,   __a    ,   __a	):
										if start > size // 2 - 1:
													return
										else:
													if 2 * start + 2 >= size:
																__lowerCAmelCase				    =			2 * start + 1
													else:
																if heap[2 * start + 1] < heap[2 * start + 2]:
																			__lowerCAmelCase				    =			2 * start + 1
																else:
																			__lowerCAmelCase				    =			2 * start + 2
													if heap[smallest_child] < heap[start]:
																__lowerCAmelCase    ,	__lowerCAmelCase				    =			heap[smallest_child], positions[smallest_child]
																__lowerCAmelCase    ,	__lowerCAmelCase				    =			(
																    heap[start],
																    positions[start],
																)
																__lowerCAmelCase    ,	__lowerCAmelCase				    =			temp, tempa

																__lowerCAmelCase				    =			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    ,   __a    ,   __a    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			position[index]

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

													if val < heap[parent]:
																__lowerCAmelCase				    =			heap[parent]
																__lowerCAmelCase				    =			position[parent]
																self.set_position(position[parent]    ,   __a	)
													else:
																__lowerCAmelCase				    =			val
																__lowerCAmelCase				    =			temp
																self.set_position(__a    ,   __a	)
																break
													__lowerCAmelCase				    =			parent
										else:
													__lowerCAmelCase				    =			val
													__lowerCAmelCase				    =			temp
													self.set_position(__a    ,   0	)

							def 			snake_case				(     self    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			len(__a	) // 2 - 1
										for i in range(__a    ,   -1    ,   -1	):
													self.top_to_bottom(__a    ,   __a    ,   len(__a	)    ,   __a	)



							def 			snake_case				(     self    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			positions[0]
										__lowerCAmelCase				    =			sys.maxsize
										self.top_to_bottom(__a    ,   0    ,   len(__a	)    ,   __a	)
										return temp


def _lowerCamelCase	(		_UpperCamelCase      ):

			'''simple docstring'''




			__lowerCAmelCase				    =			Heap()

			__lowerCAmelCase				    =			[0] * len(_UpperCamelCase      )
			__lowerCAmelCase				    =			[-1] * len(_UpperCamelCase      )  # Neighboring Tree Vertex of selected vertex
			# Minimum Distance of explored vertex with neighboring vertex of partial tree
			# formed in graph
			__lowerCAmelCase				    =			[]  # Heap of Distance of vertices from their neighboring vertex
			__lowerCAmelCase				    =			[]

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

			__lowerCAmelCase				    =			[]
			__lowerCAmelCase				    =			1
			__lowerCAmelCase				    =			sys.maxsize
			for neighbor, distance in adjacency_list[0]:
						__lowerCAmelCase				    =			0
						__lowerCAmelCase				    =			distance
			heap.heapify(_UpperCamelCase    , _UpperCamelCase      )

			for _ in range(1    , len(_UpperCamelCase      )      ):
						__lowerCAmelCase				    =			heap.delete_minimum(_UpperCamelCase    , _UpperCamelCase      )
						if visited[vertex] == 0:
									tree_edges.append((nbr_tv[vertex], vertex)      )
									__lowerCAmelCase				    =			1
									for neighbor, distance in adjacency_list[vertex]:
												if (
												    visited[neighbor] == 0
												    and distance < distance_tv[heap.get_position(_UpperCamelCase      )]
												):
															__lowerCAmelCase				    =			distance
															heap.bottom_to_top(
															    _UpperCamelCase    , heap.get_position(_UpperCamelCase      )    , _UpperCamelCase    , _UpperCamelCase      )
															__lowerCAmelCase				    =			vertex
			return tree_edges


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




