
'''simple docstring'''





import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


if TYPE_CHECKING:
	import sqlitea

	import sqlalchemy


a__						:				List[str]           =    datasets.utils.logging.get_logger(__name__)


@dataclass
class 	UpperCamelCase__					(      datasets.BuilderConfig):
	UpperCAmelCase__      :      Any  			=   None
	UpperCAmelCase__      :      str  			=   None
	UpperCAmelCase__      :      Union[str, Any]  			=   None
	UpperCAmelCase__      :      Optional[int]  			=   True
	UpperCAmelCase__      :      List[Any]  			=   None
	UpperCAmelCase__      :      Dict  			=   None
	UpperCAmelCase__      :      Optional[Any]  			=   None
	UpperCAmelCase__      :      Optional[Any]  			=   1_0_0_0_0
	UpperCAmelCase__      :      str  			=   None






	def 		lowercase_  (     self					:str     )			->     Dict:







							'''simple docstring'''



							if self.sql is None:
													raise ValueError('sql must be specified'     )
							if self.con is None:
													raise ValueError('con must be specified'     )






	def 		lowercase_  (     self					:List[str]		,			_A					:List[Any]		,			_A					:Any = None		,			)			->     List[str]:







							'''simple docstring'''



							__A    		=     config_kwargs.copy()
							# We need to stringify the Selectable object to make its hash deterministic

							# The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
							__A    		=     config_kwargs["sql"]
							if not isinstance(lowercase__		,			lowercase__     ):
													if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
																			import sqlalchemy

																			if isinstance(lowercase__		,			sqlalchemy.sql.Selectable     ):
																									__A    		=     sqlalchemy.create_engine(config_kwargs['con'].split('://'     )[0] + '://'     )
																									__A    		=     str(sql.compile(dialect=engine.dialect     )     )
																									__A    		=     sql_str
																			else:
																									raise TypeError(
																									    F'Supported types for \'sql\' are string and sqlalchemy.sql.Selectable but got {type(lowercase__     )}: {sql}'     )
													else:
																			raise TypeError(
																			    F'Supported types for \'sql\' are string and sqlalchemy.sql.Selectable but got {type(lowercase__     )}: {sql}'     )
							__A    		=     config_kwargs["con"]
							if not isinstance(lowercase__		,			lowercase__     ):
													__A    		=     id(lowercase__     )
													logger.info(
													    F'SQL connection \'con\' of type {type(lowercase__     )} couldn\'t be hashed properly. To enable hashing, specify \'con\' as URI string instead.'     )

							return super().create_config_id(lowercase__		,			custom_features=lowercase__     )






	@property
	def 		lowercase_  (     self					:Optional[Any]     )			->     Union[str, Any]:







							'''simple docstring'''



							__A    		=     {
							    "index_col": self.index_col,
							    "columns": self.columns,
							    "params": self.params,
							    "coerce_float": self.coerce_float,
							    "parse_dates": self.parse_dates,
							}
							return pd_read_sql_kwargs


class 	UpperCamelCase__					(      datasets.ArrowBasedBuilder):
	UpperCAmelCase__      :      Union[str, Any]  			=   SqlConfig






	def 		lowercase_  (     self					:Dict     )			->     Optional[int]:







							'''simple docstring'''



							return datasets.DatasetInfo(features=self.config.features     )






	def 		lowercase_  (     self					:Union[str, Any]		,			_A					:Tuple     )			->     Optional[int]:







							'''simple docstring'''



							return [datasets.SplitGenerator(name=datasets.Split.TRAIN		,			gen_kwargs={}     )]






	def 		lowercase_  (     self					:Dict		,			_A					:Any     )			->     Tuple:







							'''simple docstring'''



							if self.config.features is not None:
													__A    		=     self.config.features.arrow_schema
													if all(not require_storage_cast(lowercase__     ) for feature in self.config.features.values()     ):
																			# cheaper cast
																			__A    		=     pa.Table.from_arrays([pa_table[field.name] for field in schema]		,			schema=lowercase__     )
													else:
																			# more expensive cast; allows str <-> int/float or str to Audio for example
																			__A    		=     table_cast(lowercase__		,			lowercase__     )
							return pa_table






	def 		lowercase_  (     self					:Optional[int]     )			->     Optional[int]:







							'''simple docstring'''



							__A    		=     self.config.chunksize
							__A    		=     pd.read_sql(
							    self.config.sql		,			self.config.con		,			chunksize=lowercase__		,			**self.config.pd_read_sql_kwargs     )
							__A    		=     [sql_reader] if chunksize is None else sql_reader
							for chunk_idx, df in enumerate(lowercase__     ):
													__A    		=     pa.Table.from_pandas(lowercase__     )
													yield chunk_idx, self._cast_table(lowercase__     )








'''simple docstring'''





from __future__ import annotations





def     snake_case							(						UpperCAmelCase		)->     List[Any]:







      """simple docstring"""
      global graph, reversed_graph, scc, component, visit, stack
      if visit[u]:
            return
      __A    		=     True
      for v in graph[u]:
            dfs(UpperCAmelCase		)
      stack.append(UpperCAmelCase		)





def     snake_case							(						UpperCAmelCase		)->     List[Any]:







      """simple docstring"""
      global graph, reversed_graph, scc, component, visit, stack
      if visit[u]:
            return
      __A    		=     True
      component.append(UpperCAmelCase		)
      for v in reversed_graph[u]:
            dfsa(UpperCAmelCase		)





def     snake_case							(						)->     Any:







      """simple docstring"""
      global graph, reversed_graph, scc, component, visit, stack
      for i in range(UpperCAmelCase		):
            dfs(UpperCAmelCase		)
      __A    		=     [False] * n
      for i in stack[::-1]:
            if visit[i]:
                  continue
            __A    		=     []
            dfsa(UpperCAmelCase		)
            scc.append(UpperCAmelCase		)
      return scc


if __name__ == "__main__":
 # n - no of nodes, m - no of edges
 a__    ,						a__						:				Tuple           =    list(map(int, input().strip().split()))

 a__						:				list[list[int]]           =    [[] for _ in range(n)]  # graph
 a__						:				list[list[int]]           =    [[] for i in range(n)]  # reversed graph
 # input graph data (edges)
 for _ in range(m):
  a__    ,						a__						:				Tuple           =    list(map(int, input().strip().split()))
  graph[u].append(v)
  reversed_graph[v].append(u)

 a__						:				list[int]           =    []
 a__						:				list[bool]           =    [False] * n
 a__						:				list[int]           =    []
 a__						:				list[int]           =    []
 print(kosaraju())






