'''simple docstring'''





import json
import os
import re
import warnings
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__snake_case			      =    logging.get_logger(__name__)

__snake_case			      =    {
    '''source_spm''': '''source.spm''',
    '''target_spm''': '''target.spm''',
    '''vocab''': '''vocab.json''',
    '''target_vocab_file''': '''target_vocab.json''',
    '''tokenizer_config_file''': '''tokenizer_config.json''',
}

__snake_case			      =    {
    '''source_spm''': {
        '''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/source.spm'''
    },
    '''target_spm''': {
        '''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/target.spm'''
    },
    '''vocab''': {
        '''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/vocab.json'''
    },
    '''tokenizer_config_file''': {
        '''Helsinki-NLP/opus-mt-en-de''': (
            '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/tokenizer_config.json'''
        )
    },
}

__snake_case			      =    {'''Helsinki-NLP/opus-mt-en-de''': 5_12}
__snake_case			      =    {}







class 			__snake_case   (     lowerCamelCase__   ):
 __lowerCamelCase    :   str     =      VOCAB_FILES_NAMES
 __lowerCamelCase    :   Union[str, Any]     =      PRETRAINED_VOCAB_FILES_MAP
 __lowerCamelCase    :   int     =      PRETRAINED_INIT_CONFIGURATION
 __lowerCamelCase    :   Optional[Any]     =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __lowerCamelCase    :   List[str]     =      ["""input_ids""", """attention_mask"""]
 __lowerCamelCase    :   Optional[Any]     =      re.compile(""">>.+<<"""   )  # type: re.Pattern
 def __init__(  self		,   snake_case__		,   snake_case__		,   snake_case__		,   snake_case__=None		,   snake_case__=None		,   snake_case__=None		,   snake_case__="<unk>"		,   snake_case__="</s>"		,   snake_case__="<pad>"		,   snake_case__=512		,   snake_case__ = None		,   snake_case__=False		,   **snake_case__		,   )	->							None:
       '''simple docstring'''





       UpperCAmelCase    : List[str]      ={} if sp_model_kwargs is None else sp_model_kwargs

       super().__init__(
           # bos_token=bos_token,  unused. Start decoding with config.decoder_start_token_id
           source_lang=snake_case__		,   target_lang=snake_case__		,   unk_token=snake_case__		,   eos_token=snake_case__		,   pad_token=snake_case__		,   model_max_length=snake_case__		,   sp_model_kwargs=self.sp_model_kwargs		,   target_vocab_file=snake_case__		,   separate_vocabs=snake_case__		,   **snake_case__		,   )
       assert Path(snake_case__						).exists(), f'''cannot find spm source {source_spm}'''

       UpperCAmelCase    : Optional[Any]      =separate_vocabs
       UpperCAmelCase    : int      =load_json(snake_case__						)
       if self.unk_token not in self.encoder:
             raise KeyError('''<unk> token must be in vocab'''						)
       assert self.pad_token in self.encoder

       if separate_vocabs:
             UpperCAmelCase    : List[Any]      =load_json(snake_case__						)
             UpperCAmelCase    : Dict      ={v: k for k, v in self.target_encoder.items()}
             UpperCAmelCase    : int      =[]
       else:
             UpperCAmelCase    : List[Any]      ={v: k for k, v in self.encoder.items()}
             UpperCAmelCase    : list      =[k for k in self.encoder if k.startswith('''>>'''						) and k.endswith('''<<'''						)]

       UpperCAmelCase    : Any      =source_lang
       UpperCAmelCase    : List[Any]      =target_lang
       UpperCAmelCase    : str      =[source_spm, target_spm]

       # load SentencePiece model for pre-processing
       UpperCAmelCase    : Tuple      =load_spm(snake_case__		,   self.sp_model_kwargs						)
       UpperCAmelCase    : Dict      =load_spm(snake_case__		,   self.sp_model_kwargs						)
       UpperCAmelCase    : str      =self.spm_source
       UpperCAmelCase    : List[str]      =self.encoder

       # Multilingual target side: default to using first supported language code.

       self._setup_normalizer()
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       try:
             from sacremoses import MosesPunctNormalizer

             UpperCAmelCase    : str      =MosesPunctNormalizer(self.source_lang						).normalize
       except (ImportError, FileNotFoundError):
             warnings.warn('''Recommended: pip install sacremoses.'''						)
             UpperCAmelCase    : Tuple      =lambda snake_case__						: x
 def 	UpperCAmelCase__       (  self		,   snake_case__						)	->							str:
       '''simple docstring'''





       return self.punc_normalizer(snake_case__						) if x else ""
 def 	UpperCAmelCase__       (  self		,   snake_case__						)	->							List[Any]:
       '''simple docstring'''





       return self.current_encoder.get(snake_case__		,   self.current_encoder[self.unk_token]						)
 def 	UpperCAmelCase__       (  self		,   snake_case__						)	->							Union[str, Any]:
       '''simple docstring'''





       UpperCAmelCase    : int      =self.language_code_re.match(snake_case__						)
       UpperCAmelCase    : list      =[match.group(0						)] if match else []
       return code, self.language_code_re.sub(''''''		,   snake_case__						)
 def 	UpperCAmelCase__       (  self		,   snake_case__						)	->							List[str]:
       '''simple docstring'''





       UpperCAmelCase    : Dict      =self.remove_language_code(snake_case__						)
       UpperCAmelCase    : str      =self.current_spm.encode(snake_case__		,   out_type=snake_case__						)
       return code + pieces
 def 	UpperCAmelCase__       (  self		,   snake_case__						)	->							str:
       '''simple docstring'''





       return self.decoder.get(snake_case__		,   self.unk_token						)
 def 	UpperCAmelCase__       (  self		,   snake_case__		,   **snake_case__						)	->							int:
       '''simple docstring'''





       return super().batch_decode(snake_case__		,   **snake_case__						)
 def 	UpperCAmelCase__       (  self		,   snake_case__		,   **snake_case__						)	->							List[str]:
       '''simple docstring'''





       return super().decode(snake_case__		,   **snake_case__						)
 def 	UpperCAmelCase__       (  self		,   snake_case__						)	->							str:
       '''simple docstring'''





       UpperCAmelCase    : List[str]      =self.spm_source if self._decode_use_source_tokenizer else self.spm_target
       UpperCAmelCase    : Tuple      =[]
       UpperCAmelCase    : List[Any]      =''''''
       for token in tokens:
             # make sure that special tokens are not decoded using sentencepiece model
             if token in self.all_special_tokens:
                   out_string += sp_model.decode_pieces(snake_case__						) + token + " "
                   UpperCAmelCase    : Tuple      =[]
             else:
                   current_sub_tokens.append(snake_case__						)
       out_string += sp_model.decode_pieces(snake_case__						)
       return out_string.strip()
 def 	UpperCAmelCase__       (  self		,   snake_case__		,   snake_case__=None						)	->							List[int]:
       '''simple docstring'''





       if token_ids_a is None:
             return token_ids_a + [self.eos_token_id]
       # We don't expect to process pairs, but leave the pair logic for API consistency
       return token_ids_a + token_ids_a + [self.eos_token_id]
 def 	UpperCAmelCase__       (  self						)	->							str:
       '''simple docstring'''





       UpperCAmelCase    : Dict      =self.spm_source
       UpperCAmelCase    : List[str]      =self.encoder
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       UpperCAmelCase    : Union[str, Any]      =self.spm_target
       if self.separate_vocabs:
             UpperCAmelCase    : Union[str, Any]      =self.target_encoder
 @property
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       return len(self.encoder						)
 def 	UpperCAmelCase__       (  self		,   snake_case__		,   snake_case__ = None						)	->							Tuple[str]:
       '''simple docstring'''





       if not os.path.isdir(snake_case__						):
             logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''						)
             return
       UpperCAmelCase    : List[str]      =[]

       if self.separate_vocabs:
             UpperCAmelCase    : Optional[int]      =os.path.join(
                 snake_case__		,   (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab''']		,   )
             UpperCAmelCase    : Union[str, Any]      =os.path.join(
                 snake_case__		,   (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''target_vocab_file''']		,   )
             save_json(self.encoder		,   snake_case__						)
             save_json(self.target_encoder		,   snake_case__						)
             saved_files.append(snake_case__						)
             saved_files.append(snake_case__						)
       else:
             UpperCAmelCase    : Any      =os.path.join(
                 snake_case__		,   (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab''']						)
             save_json(self.encoder		,   snake_case__						)
             saved_files.append(snake_case__						)

       for spm_save_filename, spm_orig_path, spm_model in zip(
           [VOCAB_FILES_NAMES['''source_spm'''], VOCAB_FILES_NAMES['''target_spm''']]		,   self.spm_files		,   [self.spm_source, self.spm_target]		,   ):
             UpperCAmelCase    : List[str]      =os.path.join(
                 snake_case__		,   (filename_prefix + '''-''' if filename_prefix else '''''') + spm_save_filename						)
             if os.path.abspath(snake_case__						) != os.path.abspath(snake_case__						) and os.path.isfile(snake_case__						):
                   copyfile(snake_case__		,   snake_case__						)
                   saved_files.append(snake_case__						)
             elif not os.path.isfile(snake_case__						):
                   with open(snake_case__		,   '''wb'''						) as fi:
                         UpperCAmelCase    : int      =spm_model.serialized_model_proto()
                         fi.write(snake_case__						)
                   saved_files.append(snake_case__						)

       return tuple(snake_case__						)
 def 	UpperCAmelCase__       (  self						)	->							Dict:
       '''simple docstring'''





       return self.get_src_vocab()
 def 	UpperCAmelCase__       (  self						)	->							int:
       '''simple docstring'''





       return dict(self.encoder		,   **self.added_tokens_encoder						)
 def 	UpperCAmelCase__       (  self						)	->							Dict:
       '''simple docstring'''





       return dict(self.target_encoder		,   **self.added_tokens_decoder						)
 def __getstate__(  self						)	->							Dict:
       '''simple docstring'''





       UpperCAmelCase    : Union[str, Any]      =self.__dict__.copy()
       state.update(
           {k: None for k in ['''spm_source''', '''spm_target''', '''current_spm''', '''punc_normalizer''', '''target_vocab_file''']}						)
       return state
 def __setstate__(  self		,   snake_case__						)	->							None:
       '''simple docstring'''





       UpperCAmelCase    : Any      =d

       # for backward compatibility
       if not hasattr(self		,   '''sp_model_kwargs'''						):
             UpperCAmelCase    : Optional[Any]      ={}

       UpperCAmelCase    : Any      =(load_spm(snake_case__		,   self.sp_model_kwargs						) for f in self.spm_files)
       UpperCAmelCase    : int      =self.spm_source
       self._setup_normalizer()
 def 	UpperCAmelCase__       (  self		,   *snake_case__		,   **snake_case__						)	->							Any:
       '''simple docstring'''





       return 1
 def 	UpperCAmelCase__       (  self		,   snake_case__						)	->							Union[str, Any]:
       '''simple docstring'''





       UpperCAmelCase    : Dict      =set(self.all_special_ids						)  # call it once instead of inside list comp
       all_special_ids.remove(self.unk_token_id						)  # <unk> is only sometimes special
       return [1 if x in all_special_ids else 0 for x in seq]






 def 	UpperCAmelCase__       (  self		,   snake_case__		,   snake_case__ = None		,   snake_case__ = False						)	->							List[int]:
       '''simple docstring'''





       if already_has_special_tokens:
             return self._special_token_mask(snake_case__						)
       elif token_ids_a is None:
             return self._special_token_mask(snake_case__						) + [1]
       else:
             return self._special_token_mask(token_ids_a + token_ids_a						) + [1]





def   lowerCAmelCase_ (				__lowerCAmelCase		,					__lowerCAmelCase						)->  sentencepiece.SentencePieceProcessor:






      '''simple docstring'''





      UpperCAmelCase    : Tuple      =sentencepiece.SentencePieceProcessor(**__lowerCAmelCase						)
      spm.Load(__lowerCAmelCase						)
      return spm





def   lowerCAmelCase_ (				__lowerCAmelCase		,					__lowerCAmelCase						)->  None:






      '''simple docstring'''





      with open(__lowerCAmelCase		,					'''w'''						) as f:
            json.dump(__lowerCAmelCase		,					__lowerCAmelCase		,					indent=2						)





def   lowerCAmelCase_ (				__lowerCAmelCase						)->  Union[Dict, List]:






      '''simple docstring'''





      with open(__lowerCAmelCase		,					'''r'''						) as f:
            return json.load(__lowerCAmelCase						)

def   lowerCAmelCase_ (				__lowerCAmelCase		,					__lowerCAmelCase						)->  list[tuple[int, int, int]]:






      '''simple docstring'''





      UpperCAmelCase    : List[Any]      =sorted(__lowerCAmelCase		,					key=lambda __lowerCAmelCase						: edge[2]						)

      UpperCAmelCase    : Union[str, Any]      =list(range(__lowerCAmelCase						)						)

      def find_parent(__lowerCAmelCase						):
            if i != parent[i]:
                  UpperCAmelCase    : Optional[int]      =find_parent(parent[i]						)
            return parent[i]

      UpperCAmelCase    : Optional[Any]      =0
      UpperCAmelCase    : List[str]      =[]

      for edge in edges:
            UpperCAmelCase    : Dict      =find_parent(edge[0]						)
            UpperCAmelCase    : Optional[Any]      =find_parent(edge[1]						)
            if parent_a != parent_b:
                  minimum_spanning_tree_cost += edge[2]
                  minimum_spanning_tree.append(__lowerCAmelCase						)
                  UpperCAmelCase    : Optional[Any]      =parent_b

      return minimum_spanning_tree


if __name__ == "__main__":  # pragma: no cover
     __snake_case      ,  __snake_case			      =    list(map(int, input().strip().split()))
     __snake_case			      =    []

     for _ in range(num_edges):
          __snake_case      ,  __snake_case      ,  __snake_case			      =    (int(x) for x in input().strip().split())
          edges.append((nodea, nodea, cost))

     kruskal(num_nodes, edges)
