


'''simple docstring'''



import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import datasets
import numpy as np
import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    PreTrainedTokenizer,
    TFAutoModelForSequenceClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()



def      UpperCAmelCase__   (      UpperCAmelCase_       :							str ,       UpperCAmelCase_       :							str ,       UpperCAmelCase_       :							str ,       UpperCAmelCase_       :							PreTrainedTokenizer ,       UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							Optional[int] = None ,       )	->						Tuple:
     __lowerCamelCase  :      Any														=						{}

     if train_file is not None:
          __lowerCamelCase  :      int														=						[train_file]
     if eval_file is not None:
          __lowerCamelCase  :      Any														=						[eval_file]
     if test_file is not None:
          __lowerCamelCase  :      Any														=						[test_file]

     __lowerCamelCase  :      Any														=						datasets.load_dataset('csv' ,       data_files=UpperCAmelCase_				)
     __lowerCamelCase  :      Dict														=						list(ds[list(files.keys()				)[0]].features.keys()				)
     __lowerCamelCase  :      Union[str, Any]														=						features_name.pop(UpperCAmelCase_				)
     __lowerCamelCase  :      Optional[Any]														=						list(set(ds[list(files.keys()				)[0]][label_name]				)				)
     __lowerCamelCase  :      Union[str, Any]														=						{label: i for i, label in enumerate(UpperCAmelCase_				)}
     __lowerCamelCase  :      Optional[Any]														=						tokenizer.model_input_names
     __lowerCamelCase  :      Optional[int]														=						{}

     if len(UpperCAmelCase_				) == 1:
          for k in files.keys():
               __lowerCamelCase  :      str														=						ds[k].map(
                   lambda UpperCAmelCase_				: tokenizer.batch_encode_plus(
                       example[features_name[0]] ,       truncation=UpperCAmelCase_ ,       max_length=UpperCAmelCase_ ,       padding='max_length'				) ,       batched=UpperCAmelCase_ ,       )
     elif len(UpperCAmelCase_				) == 2:
          for k in files.keys():
               __lowerCamelCase  :      Union[str, Any]														=						ds[k].map(
                   lambda UpperCAmelCase_				: tokenizer.batch_encode_plus(
                       (example[features_name[0]], example[features_name[1]]) ,       truncation=UpperCAmelCase_ ,       max_length=UpperCAmelCase_ ,       padding='max_length' ,       ) ,       batched=UpperCAmelCase_ ,       )

     def gen_train():
          for ex in transformed_ds[datasets.Split.TRAIN]:
               __lowerCamelCase  :      Any														=						{k: v for k, v in ex.items() if k in input_names}
               __lowerCamelCase  :      Dict														=						labelaid[ex[label_name]]
               yield (d, label)

     def gen_val():
          for ex in transformed_ds[datasets.Split.VALIDATION]:
               __lowerCamelCase  :      List[Any]														=						{k: v for k, v in ex.items() if k in input_names}
               __lowerCamelCase  :      int														=						labelaid[ex[label_name]]
               yield (d, label)

     def gen_test():
          for ex in transformed_ds[datasets.Split.TEST]:
               __lowerCamelCase  :      Optional[int]														=						{k: v for k, v in ex.items() if k in input_names}
               __lowerCamelCase  :      List[str]														=						labelaid[ex[label_name]]
               yield (d, label)

     __lowerCamelCase  :      List[Any]														=						(
         tf.data.Dataset.from_generator(
             UpperCAmelCase_ ,       ({k: tf.intaa for k in input_names}, tf.intaa) ,       ({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				)) ,       )
         if datasets.Split.TRAIN in transformed_ds
         else None
     )

     if train_ds is not None:
          __lowerCamelCase  :      Optional[Any]														=						train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN]				)				)				)

     __lowerCamelCase  :      Union[str, Any]														=						(
         tf.data.Dataset.from_generator(
             UpperCAmelCase_ ,       ({k: tf.intaa for k in input_names}, tf.intaa) ,       ({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				)) ,       )
         if datasets.Split.VALIDATION in transformed_ds
         else None
     )

     if val_ds is not None:
          __lowerCamelCase  :      Optional[int]														=						val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION]				)				)				)

     __lowerCamelCase  :      List[Any]														=						(
         tf.data.Dataset.from_generator(
             UpperCAmelCase_ ,       ({k: tf.intaa for k in input_names}, tf.intaa) ,       ({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				)) ,       )
         if datasets.Split.TEST in transformed_ds
         else None
     )

     if test_ds is not None:
          __lowerCamelCase  :      List[str]														=						test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST]				)				)				)

     return train_ds, val_ds, test_ds, labelaid


A__						:   int				=    logging.getLogger(__name__)





@dataclass
class   UpperCAmelCase_    :





    """simple docstring"""






    lowerCamelCase    :   int					=     field(metadata={'help': 'Which column contains the label'}    )
    lowerCamelCase    :   str					=     field(default=_UpperCAmelCase   ,						metadata={'help': 'The path of the training file'}    )
    lowerCamelCase    :   Optional[str]					=     field(default=_UpperCAmelCase   ,						metadata={'help': 'The path of the development file'}    )
    lowerCamelCase    :   Optional[str]					=     field(default=_UpperCAmelCase   ,						metadata={'help': 'The path of the test file'}    )
    lowerCamelCase    :   int					=     field(
        default=1_2_8   ,						metadata={
            'help': (
                'The maximum total input sequence length after tokenization. Sequences longer '
                'than this will be truncated, sequences shorter will be padded.'
            )
        }   ,						)
    lowerCamelCase    :   bool					=     field(
        default=_UpperCAmelCase   ,						metadata={'help': 'Overwrite the cached training and evaluation sets'}    )







@dataclass
class   UpperCAmelCase_    :





    """simple docstring"""






    lowerCamelCase    :   str					=     field(
        metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}    )
    lowerCamelCase    :   Optional[str]					=     field(
        default=_UpperCAmelCase   ,						metadata={'help': 'Pretrained config name or path if not the same as model_name'}    )
    lowerCamelCase    :   Optional[str]					=     field(
        default=_UpperCAmelCase   ,						metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}    )
    lowerCamelCase    :   bool					=     field(default=_UpperCAmelCase   ,						metadata={'help': 'Set this flag to use fast tokenization.'}    )
    # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
    # or just modify its tokenizer_config.json.
    lowerCamelCase    :   Optional[str]					=     field(
        default=_UpperCAmelCase   ,						metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}   ,						)







def      UpperCAmelCase__   (      )	->						str:
     # See all possible arguments in src/transformers/training_args.py
     # or by passing the --help flag to this script.
     # We now keep distinct sets of args, for a cleaner separation of concerns.
     __lowerCamelCase  :      int														=						HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)				)
     __lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase  :      Optional[Any]														=						parser.parse_args_into_dataclasses()

     if (
         os.path.exists(training_args.output_dir				)
         and os.listdir(training_args.output_dir				)
         and training_args.do_train
         and not training_args.overwrite_output_dir
     ):
          raise ValueError(
              F'Output directory ({training_args.output_dir}) already exists and is not empty. Use'
              ' --overwrite_output_dir to overcome.'				)

     # Setup logging
     logging.basicConfig(
         format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' ,       datefmt='%m/%d/%Y %H:%M:%S' ,       level=logging.INFO ,       )
     logger.info(
         F'n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1				)}, '
         F'16-bits training: {training_args.fpaa}'				)
     logger.info(F'Training/evaluation parameters {training_args}'				)

     # Load pretrained model and tokenizer
     #
     # Distributed training:
     # The .from_pretrained methods guarantee that only one local process can concurrently
     # download model & vocab.

     __lowerCamelCase  :      Optional[Any]														=						AutoTokenizer.from_pretrained(
         model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path ,       cache_dir=model_args.cache_dir ,       )

     __lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase  :      int														=						get_tfds(
         train_file=data_args.train_file ,       eval_file=data_args.dev_file ,       test_file=data_args.test_file ,       tokenizer=UpperCAmelCase_ ,       label_column_id=data_args.label_column_id ,       max_seq_length=data_args.max_seq_length ,       )

     __lowerCamelCase  :      Any														=						AutoConfig.from_pretrained(
         model_args.config_name if model_args.config_name else model_args.model_name_or_path ,       num_labels=len(UpperCAmelCase_				) ,       labelaid=UpperCAmelCase_ ,       idalabel={id: label for label, id in labelaid.items()} ,       finetuning_task='text-classification' ,       cache_dir=model_args.cache_dir ,       )

     with training_args.strategy.scope():
          __lowerCamelCase  :      Optional[int]														=						TFAutoModelForSequenceClassification.from_pretrained(
              model_args.model_name_or_path ,       from_pt=bool('.bin' in model_args.model_name_or_path				) ,       config=UpperCAmelCase_ ,       cache_dir=model_args.cache_dir ,       )

     def compute_metrics(UpperCAmelCase_       :							EvalPrediction				) -> Dict:
          __lowerCamelCase  :      Any														=						np.argmax(p.predictions ,       axis=1				)

          return {"acc": (preds == p.label_ids).mean()}

     # Initialize our Trainer
     __lowerCamelCase  :      int														=						TFTrainer(
         model=UpperCAmelCase_ ,       args=UpperCAmelCase_ ,       train_dataset=UpperCAmelCase_ ,       eval_dataset=UpperCAmelCase_ ,       compute_metrics=UpperCAmelCase_ ,       )

     # Training
     if training_args.do_train:
          trainer.train()
          trainer.save_model()
          tokenizer.save_pretrained(training_args.output_dir				)

     # Evaluation
     __lowerCamelCase  :      Optional[Any]														=						{}
     if training_args.do_eval:
          logger.info('*** Evaluate ***'				)
          __lowerCamelCase  :      List[str]														=						trainer.evaluate()
          __lowerCamelCase  :      Optional[Any]														=						os.path.join(training_args.output_dir ,       'eval_results.txt'				)

          with open(UpperCAmelCase_ ,       'w'				) as writer:
               logger.info('***** Eval results *****'				)

               for key, value in result.items():
                    logger.info(F'  {key} = {value}'				)
                    writer.write(F'{key} = {value}\n'				)

               results.update(UpperCAmelCase_				)

     return results


if __name__ == "__main__":
      main()










'''simple docstring'''



import sys
from collections import defaultdict





class   UpperCAmelCase_    :





    """simple docstring"""






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







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_      )							->	Any:
         return self.node_position[vertex]







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	Tuple:
         __lowerCamelCase  :      Optional[int]														=						pos







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

                   __lowerCamelCase  :      Dict														=						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  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	Any:
         __lowerCamelCase  :      Any														=						position[index]

         while index != 0:
              __lowerCamelCase  :      Union[str, Any]														=						int((index - 2) / 2      ) if index % 2 == 0 else int((index - 1) / 2      )

              if val < heap[parent]:
                   __lowerCamelCase  :      Union[str, Any]														=						heap[parent]
                   __lowerCamelCase  :      Any														=						position[parent]
                   self.set_position(position[parent]     ,	SCREAMING_SNAKE_CASE_      )
              else:
                   __lowerCamelCase  :      Tuple														=						val
                   __lowerCamelCase  :      List[str]														=						temp
                   self.set_position(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )
                   break
              __lowerCamelCase  :      Tuple														=						parent
         else:
              __lowerCamelCase  :      Union[str, Any]														=						val
              __lowerCamelCase  :      Tuple														=						temp
              self.set_position(SCREAMING_SNAKE_CASE_     ,	0      )







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	Optional[int]:
         __lowerCamelCase  :      Optional[int]														=						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  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	List[Any]:
         __lowerCamelCase  :      Any														=						positions[0]
         __lowerCamelCase  :      Union[str, Any]														=						sys.maxsize
         self.top_to_bottom(SCREAMING_SNAKE_CASE_     ,	0     ,	len(SCREAMING_SNAKE_CASE_      )     ,	SCREAMING_SNAKE_CASE_      )
         return temp







def      UpperCAmelCase__   (      UpperCAmelCase_       :							Optional[int]				)	->						str:
     __lowerCamelCase  :      List[Any]														=						Heap()

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

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

     __lowerCamelCase  :      Tuple														=						[]
     __lowerCamelCase  :      Dict														=						1
     __lowerCamelCase  :      str														=						sys.maxsize
     for neighbor, distance in adjacency_list[0]:
          __lowerCamelCase  :      Any														=						0
          __lowerCamelCase  :      Any														=						distance
     heap.heapify(UpperCAmelCase_ ,       UpperCAmelCase_				)

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


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






