





import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
				import torch

				UpperCAmelCase						:       Union[str, Any]        =					True
except ImportError:
				UpperCAmelCase						:       Tuple        =					False


try:
				from torch.hub import _get_torch_home

				UpperCAmelCase						:       Optional[int]        =					_get_torch_home()
except ImportError:
				UpperCAmelCase						:       Union[str, Any]        =					os.path.expanduser(
				    os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch'''))
				)

UpperCAmelCase						:       str        =					os.path.join(torch_cache_home, '''transformers''')

UpperCAmelCase						:       Any        =					'''https://cdn.huggingface.co'''
UpperCAmelCase						:       Any        =					'''https://s3.amazonaws.com/models.huggingface.co/bert'''
UpperCAmelCase						:       List[Any]        =					'''/'''.join(str(Path(__file__).resolve()).split('''/''')[:-1])
UpperCAmelCase						:       List[str]        =					os.path.join(PATH, '''config.yaml''')
UpperCAmelCase						:       List[Any]        =					os.path.join(PATH, '''attributes.txt''')
UpperCAmelCase						:       int        =					os.path.join(PATH, '''objects.txt''')
UpperCAmelCase						:       str        =					os.getenv('''PYTORCH_PRETRAINED_BERT_CACHE''', default_cache_path)
UpperCAmelCase						:       List[str]        =					os.getenv('''PYTORCH_TRANSFORMERS_CACHE''', PYTORCH_PRETRAINED_BERT_CACHE)
UpperCAmelCase						:       Any        =					os.getenv('''TRANSFORMERS_CACHE''', PYTORCH_TRANSFORMERS_CACHE)
UpperCAmelCase						:       Dict        =					'''pytorch_model.bin'''
UpperCAmelCase						:       Dict        =					'''config.yaml'''







def 			_SCREAMING_SNAKE_CASE    (       a=OBJECTS ,						a=ATTRIBUTES  )				->				List[Any]:
					__A     :						List[Any]          =    []
					with open(a  ) as f:
										for object in f.readlines():
															vg_classes.append(object.split(','  )[0].lower().strip()  )

					__A     :						Any          =    []
					with open(a  ) as f:
										for object in f.readlines():
															vg_attrs.append(object.split(','  )[0].lower().strip()  )
					return vg_classes, vg_attrs







def 			_SCREAMING_SNAKE_CASE    (       a  )				->				Tuple:
					__A     :						Dict          =    OrderedDict()
					with open(a ,						'rb'  ) as f:
										__A     :						str          =    pkl.load(a  )['model']
					for k in copy.deepcopy(list(ckp.keys()  )  ):
										__A     :						Any          =    ckp.pop(a  )
										if isinstance(a ,						np.ndarray  ):
															__A     :						Union[str, Any]          =    torch.tensor(a  )
										else:
															assert isinstance(a ,						torch.tensor  ), type(a  )
										__A     :						Tuple          =    v
					return r





class 						_A:


				"""simple docstring"""


				UpperCamelCase   :  Tuple    =     {}



				def __init__(      self					, _A					, _A = "root"					, _A=0					):
									__A     :						str          =    name
									__A     :						Tuple          =    level
									__A     :						List[str]          =    {}
									for k, v in dictionary.items():
														if v is None:
																			raise ValueError()
														__A     :						int          =    copy.deepcopy(_A					)
														__A     :						Union[str, Any]          =    copy.deepcopy(_A					)
														if isinstance(_A					, _A					):
																			__A     :						Union[str, Any]          =    Config(_A					, name=_A					, level=level + 1					)
														__A     :						Union[str, Any]          =    v
														setattr(self					, _A					, _A					)

									__A     :						List[Any]          =    d



				def __repr__(      self					):
									return str(list((self._pointer.keys())					)					)



				def __setattr__(      self					, _A					, _A					):
									__A     :						int          =    val
									__A     :						Tuple          =    val
									__A     :						int          =    key.split('.'					)
									__A     :						Union[str, Any]          =    len(_A					) - 1
									__A     :						Optional[Any]          =    self._pointer
									if len(_A					) > 1:
														for i, l in enumerate(_A					):
																			if hasattr(self					, _A					) and isinstance(getattr(self					, _A					)					, _A					):
																								setattr(getattr(self					, _A					)					, '.'.join(levels[i:]					)					, _A					)
																			if l == last_level:
																								__A     :						Dict          =    val
																			else:
																								__A     :						Optional[int]          =    pointer[l]



				def  UpperCAmelCase_		(      self					):
									return self._pointer



				def  UpperCAmelCase_		(      self					, _A					, _A					):
									with open(F"""{file_name}"""					, 'w'					) as stream:
														dump(_A					, _A					)



				def  UpperCAmelCase_		(      self					, _A					, _A					):
									with open(F"""{file_name}"""					, 'w'					) as stream:
														json.dump(_A					, _A					)



				@staticmethod
				def  UpperCAmelCase_		(      _A					):
									with open(_A					) as stream:
														__A     :						Tuple          =    load(_A					, Loader=_A					)
									return data



				def __str__(      self					):
									__A     :						List[Any]          =    '    '
									if self._name != "root":
														__A     :						List[Any]          =    F"""{t * (self._level-1)}{self._name}:\n"""
									else:
														__A     :						Union[str, Any]          =    ''
									__A     :						Union[str, Any]          =    self._level
									for i, (k, v) in enumerate(self._pointer.items()					):
														if isinstance(_A					, _A					):
																			r += F"""{t * (self._level)}{v}\n"""
																			self._level += 1
														else:
																			r += F"""{t * (self._level)}{k}: {v} ({type(_A					).__name__})\n"""
														__A     :						List[Any]          =    level
									return r[:-1]



				@classmethod
				def  UpperCAmelCase_		(      cls					, _A					, **_A					):
									__A   ,    __A     :						List[str]          =    cls.get_config_dict(_A					, **_A					)
									return cls(_A					)





				@classmethod
				def  UpperCAmelCase_		(      cls					, _A					, **_A					):
									__A     :						List[str]          =    kwargs.pop('cache_dir'					, _A					)
									__A     :						List[str]          =    kwargs.pop('force_download'					, _A					)
									__A     :						Dict          =    kwargs.pop('resume_download'					, _A					)
									__A     :						List[Any]          =    kwargs.pop('proxies'					, _A					)
									__A     :						Tuple          =    kwargs.pop('local_files_only'					, _A					)

									if os.path.isdir(_A					):
														__A     :						List[Any]          =    os.path.join(_A					, _A					)
									elif os.path.isfile(_A					) or is_remote_url(_A					):
														__A     :						List[str]          =    pretrained_model_name_or_path
									else:
														__A     :						Optional[int]          =    hf_bucket_url(_A					, filename=_A					, use_cdn=_A					)

									try:
														# Load from URL or cache if already cached
														__A     :						Optional[Any]          =    cached_path(
														    _A					, cache_dir=_A					, force_download=_A					, proxies=_A					, resume_download=_A					, local_files_only=_A					, )
														# Load config dict
														if resolved_config_file is None:
																			raise EnvironmentError

														__A     :						Tuple          =    Config.load_yaml(_A					)

									except EnvironmentError:
														__A     :						Optional[int]          =    'Can\'t load config for'
														raise EnvironmentError(_A					)

									if resolved_config_file == config_file:
														print('loading configuration file from path'					)
									else:
														print('loading configuration file cache'					)

									return Config.load_yaml(_A					), kwargs







def 			_SCREAMING_SNAKE_CASE    (       a  )				->				Any:
					__A     :						int          =    torch.load('dump.pt' ,						map_location=in_tensor.device  )
					__A     :						Optional[Any]          =    in_tensor.numpy()
					__A     :						Optional[Any]          =    out_tensor.numpy()[0]
					print(na.shape ,						na[0, 0, :5]  )
					print(na.shape ,						na[0, 0, :5]  )
					assert np.allclose(a ,						a ,						rtol=0.01 ,						atol=0.1  ), (
					    F"""{sum([1 for x in np.isclose(a ,						a ,						rtol=0.01 ,						atol=0.1  ).flatten() if x is False]  )/len(na.flatten()  )*1_00:.4f} %"""
					    " element-wise mismatch"
					)
					raise Exception('tensors are all good'  )

					# Hugging face functions below







def 			_SCREAMING_SNAKE_CASE    (       a  )				->				Any:
					__A     :						str          =    urlparse(a  )
					return parsed.scheme in ("http", "https")







def 			_SCREAMING_SNAKE_CASE    (       a ,						a ,						a=True  )				->				str:
					__A     :						List[str]          =    CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
					__A     :						List[str]          =    '/' not in model_id
					if legacy_format:
										return F"""{endpoint}/{model_id}-{filename}"""
					else:
										return F"""{endpoint}/{model_id}/{filename}"""







def 			_SCREAMING_SNAKE_CASE    (       a ,						a ,						a=None ,						a=0 ,						a=None ,						)				->				Tuple:
					__A     :						List[str]          =    'python/{}'.format(sys.version.split()[0]  )
					if _torch_available:
										ua += "; torch/{}".format(torch.__version__  )
					if isinstance(a ,						a  ):
										ua += "; " + "; ".join('{}/{}'.format(a ,						a  ) for k, v in user_agent.items()  )
					elif isinstance(a ,						a  ):
										ua += "; " + user_agent
					__A     :						Dict          =    {'user-agent': ua}
					if resume_size > 0:
										__A     :						Dict          =    'bytes=%d-' % (resume_size,)
					__A     :						Dict          =    requests.get(a ,						stream=a ,						proxies=a ,						headers=a  )
					if response.status_code == 4_16:  # Range not satisfiable
										return
					__A     :						List[str]          =    response.headers.get('Content-Length'  )
					__A     :						Any          =    resume_size + int(a  ) if content_length is not None else None
					__A     :						int          =    tqdm(
					    unit='B' ,						unit_scale=a ,						total=a ,						initial=a ,						desc='Downloading' ,						)
					for chunk in response.iter_content(chunk_size=10_24  ):
										if chunk:  # filter out keep-alive new chunks
															progress.update(len(a  )  )
															temp_file.write(a  )
					progress.close()







def 			_SCREAMING_SNAKE_CASE    (       a ,						a=None ,						a=False ,						a=None ,						a=10 ,						a=False ,						a=None ,						a=False ,						)				->				List[str]:
					if cache_dir is None:
										__A     :						Dict          =    TRANSFORMERS_CACHE
					if isinstance(a ,						a  ):
										__A     :						List[str]          =    str(a  )

					os.makedirs(a ,						exist_ok=a  )

					__A     :						Any          =    None
					if not local_files_only:
										try:
															__A     :						Optional[Any]          =    requests.head(a ,						allow_redirects=a ,						proxies=a ,						timeout=a  )
															if response.status_code == 2_00:
																				__A     :						Union[str, Any]          =    response.headers.get('ETag'  )
										except (EnvironmentError, requests.exceptions.Timeout):
															# etag is already None
															pass

					__A     :						Tuple          =    url_to_filename(a ,						a  )

					# get cache path to put the file
					__A     :						str          =    os.path.join(a ,						a  )

					# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
					# try to get the last downloaded one
					if etag is None:
										if os.path.exists(a  ):
															return cache_path
										else:
															__A     :						List[Any]          =    [
															    file
															    for file in fnmatch.filter(os.listdir(a  ) ,						filename + '.*'  )
															    if not file.endswith('.json'  ) and not file.endswith('.lock'  )
															]
															if len(a  ) > 0:
																				return os.path.join(a ,						matching_files[-1]  )
															else:
																				# If files cannot be found and local_files_only=True,
																				# the models might've been found if local_files_only=False
																				# Notify the user about that
																				if local_files_only:
																									raise ValueError(
																									    'Cannot find the requested files in the cached path and outgoing traffic has been'
																									    ' disabled. To enable model look-ups and downloads online, set \'local_files_only\''
																									    ' to False.'  )
																				return None

    # From now on, etag is not None.
					if os.path.exists(a  ) and not force_download:
										return cache_path

					# Prevent parallel downloads of the same file with a lock.
					__A     :						List[Any]          =    cache_path + '.lock'
					with FileLock(a  ):
										# If the download just completed while the lock was activated.
										if os.path.exists(a  ) and not force_download:
															# Even if returning early like here, the lock will be released.
															return cache_path

										if resume_download:
															__A     :						Dict          =    cache_path + '.incomplete'

															@contextmanager
															def _resumable_file_manager():
																				with open(a ,						'a+b'  ) as f:
																									yield f

															__A     :						Optional[Any]          =    _resumable_file_manager
															if os.path.exists(a  ):
																				__A     :						str          =    os.stat(a  ).st_size
															else:
																				__A     :						Optional[int]          =    0
										else:
															__A     :						List[Any]          =    partial(tempfile.NamedTemporaryFile ,						dir=a ,						delete=a  )
															__A     :						str          =    0

										# Download to temporary file, then copy to cache dir once finished.
										# Otherwise you get corrupt cache entries if the download gets interrupted.
										with temp_file_manager() as temp_file:
															print(
															    '%s not found in cache or force_download set to True, downloading to %s' ,						a ,						temp_file.name ,						)

															http_get(
															    a ,						a ,						proxies=a ,						resume_size=a ,						user_agent=a ,						)

										os.replace(temp_file.name ,						a  )

										__A     :						List[Any]          =    {'url': url, 'etag': etag}
										__A     :						Optional[Any]          =    cache_path + '.json'
										with open(a ,						'w'  ) as meta_file:
															json.dump(a ,						a  )

					return cache_path







def 			_SCREAMING_SNAKE_CASE    (       a ,						a=None  )				->				Optional[int]:
					__A     :						int          =    url.encode('utf-8'  )
					__A     :						Optional[Any]          =    shaaaa(a  )
					__A     :						List[Any]          =    url_hash.hexdigest()

					if etag:
										__A     :						Union[str, Any]          =    etag.encode('utf-8'  )
										__A     :						str          =    shaaaa(a  )
										filename += "." + etag_hash.hexdigest()

					if url.endswith('.h5'  ):
										filename += ".h5"

					return filename







def 			_SCREAMING_SNAKE_CASE    (       a ,						a=None ,						a=False ,						a=None ,						a=False ,						a=None ,						a=False ,						a=False ,						a=False ,						)				->				int:
					if cache_dir is None:
										__A     :						int          =    TRANSFORMERS_CACHE
					if isinstance(a ,						a  ):
										__A     :						int          =    str(a  )
					if isinstance(a ,						a  ):
										__A     :						Optional[Any]          =    str(a  )

					if is_remote_url(a  ):
										# URL, so get it from the cache (downloading if necessary)
										__A     :						Optional[Any]          =    get_from_cache(
										    a ,						cache_dir=a ,						force_download=a ,						proxies=a ,						resume_download=a ,						user_agent=a ,						local_files_only=a ,						)
					elif os.path.exists(a  ):
										# File, and it exists.
										__A     :						str          =    url_or_filename
					elif urlparse(a  ).scheme == "":
										# File, but it doesn't exist.
										raise EnvironmentError('file {} not found'.format(a  )  )
					else:
										# Something unknown
										raise ValueError('unable to parse {} as a URL or as a local path'.format(a  )  )

					if extract_compressed_file:
										if not is_zipfile(a  ) and not tarfile.is_tarfile(a  ):
															return output_path

										# Path where we extract compressed archives
										# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
										__A   ,    __A     :						Optional[Any]          =    os.path.split(a  )
										__A     :						List[Any]          =    output_file.replace('.' ,						'-'  ) + '-extracted'
										__A     :						List[Any]          =    os.path.join(a ,						a  )

										if os.path.isdir(a  ) and os.listdir(a  ) and not force_extract:
															return output_path_extracted

										# Prevent parallel extractions
										__A     :						Optional[int]          =    output_path + '.lock'
										with FileLock(a  ):
															shutil.rmtree(a ,						ignore_errors=a  )
															os.makedirs(a  )
															if is_zipfile(a  ):
																				with ZipFile(a ,						'r'  ) as zip_file:
																									zip_file.extractall(a  )
																									zip_file.close()
															elif tarfile.is_tarfile(a  ):
																				__A     :						Tuple          =    tarfile.open(a  )
																				tar_file.extractall(a  )
																				tar_file.close()
															else:
																				raise EnvironmentError('Archive format of {} could not be identified'.format(a  )  )

										return output_path_extracted

					return output_path







def 			_SCREAMING_SNAKE_CASE    (       a ,						a=","  )				->				List[Any]:
					assert isinstance(a ,						a  )
					if os.path.isfile(a  ):
										with open(a  ) as f:
															__A     :						int          =    eval(f.read()  )
					else:
										__A     :						Optional[int]          =    requests.get(a  )
										try:
															__A     :						List[Any]          =    requests.json()
										except Exception:
															__A     :						Tuple          =    req.content.decode()
															assert data is not None, "could not connect"
															try:
																				__A     :						Dict          =    eval(a  )
															except Exception:
																				__A     :						Optional[Any]          =    data.split('\n'  )
										req.close()
					return data







def 			_SCREAMING_SNAKE_CASE    (       a  )				->				Any:
					__A     :						Optional[int]          =    requests.get(a  )
					__A     :						Dict          =    np.array(Image.open(BytesIO(response.content  )  )  )
					return img







def 			_SCREAMING_SNAKE_CASE    (       a  )				->				Union[str, Any]:
					__A     :						Tuple          =    url.split('/'  )[-1]
					if fn not in os.listdir(os.getcwd()  ):
										wget.download(a  )
					with open(a ,						'rb'  ) as stream:
										__A     :						List[Any]          =    pkl.load(a  )
					__A     :						str          =    weights.pop('model'  )
					__A     :						Optional[int]          =    {}
					for k, v in model.items():
										__A     :						Optional[Any]          =    torch.from_numpy(a  )
										if "running_var" in k:
															__A     :						Tuple          =    torch.tensor([0]  )
															__A     :						List[Any]          =    k.replace('running_var' ,						'num_batches_tracked'  )
															__A     :						str          =    zero
					return new







def 			_SCREAMING_SNAKE_CASE    (       )				->				List[str]:
					print(F"""{os.path.abspath(os.path.join(a ,						os.pardir  )  )}/demo.ipynb"""  )







def 			_SCREAMING_SNAKE_CASE    (       a ,						a="RGB"  )				->				Tuple:
					assert isinstance(a ,						a  )
					if os.path.isfile(a  ):
										__A     :						Dict          =    cva.imread(a  )
					else:
										__A     :						Optional[int]          =    get_image_from_url(a  )
										assert img is not None, F"""could not connect to: {im}"""
					__A     :						Dict          =    cva.cvtColor(a ,						cva.COLOR_BGR2RGB  )
					if input_format == "RGB":
										__A     :						Dict          =    img[:, :, ::-1]
					return img







def 			_SCREAMING_SNAKE_CASE    (       a ,						a=1  )				->				Tuple:
					return (images[i : i + batch] for i in range(0 ,						len(a  ) ,						a  ))











from __future__ import annotations







def 			_SCREAMING_SNAKE_CASE    (       a  )				->				List[str]:
					global graph, reversed_graph, scc, component, visit, stack
					if visit[u]:
										return
					__A     :						List[Any]          =    True
					for v in graph[u]:
										dfs(a  )
					stack.append(a  )







def 			_SCREAMING_SNAKE_CASE    (       a  )				->				Optional[Any]:
					global graph, reversed_graph, scc, component, visit, stack
					if visit[u]:
										return
					__A     :						str          =    True
					component.append(a  )
					for v in reversed_graph[u]:
										dfsa(a  )







def 			_SCREAMING_SNAKE_CASE    (       )				->				Optional[int]:
					global graph, reversed_graph, scc, component, visit, stack
					for i in range(a  ):
										dfs(a  )
					__A     :						str          =    [False] * n
					for i in stack[::-1]:
										if visit[i]:
															continue
										__A     :						Optional[Any]          =    []
										dfsa(a  )
										scc.append(a  )
					return scc


if __name__ == "__main__":
				# n - no of nodes, m - no of edges
				UpperCAmelCase  ,			UpperCAmelCase						:       List[str]        =					list(map(int, input().strip().split()))

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

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




