This documentation is automatically generated by online-judge-tools/verification-helper
from math import gcd
import cp_library.alg.graph.__header__
from typing import Iterable
from cp_library.io.parser_cls import Parsable, Parser
class FuncGraph(list[int], Parsable):
def __init__(F, successors):
super().__init__(successors)
F.N = F.M = len(F)
def find_cycle(P, root: int) -> list[int]:
slow = fast = root
while (slow := P[slow]) != (fast := P[P[fast]]): pass
cyc = [slow]
while P[slow] != fast: cyc.append(slow := P[slow])
return cyc
def cycles(P) -> 'CRFList[int]':
vis, cycs, S = u8f(N := P.N), elist(N), elist(N)
for v in range(P.N):
if vis[v]: continue
slow = fast = v
while (slow := P[slow]) != (fast := P[P[fast]]) and not vis[fast]: pass
if vis[fast]: continue
S.append(len(cycs))
cycs.append(slow)
vis[slow := P[slow]] = 1
while slow != fast:
cycs.append(slow)
vis[slow := P[slow]] = 1
return CRFList(cycs, S)
def chain(P, root):
cyc = P.find_cycle(root)
slow, fast = root, cyc[0]
if slow == fast: return [], cyc
line = [slow]
while (slow := P[slow]) != (fast := P[fast]):
line.append(slow)
return line, roll(cyc, -cyc.index(slow))
@classmethod
def compile(cls, N: int, shift = -1):
return Parser.compile_repeat(cls, shift, N)
from cp_library.alg.iter.crf_list_cls import CRFList
from cp_library.alg.iter.roll_fn import roll
from cp_library.ds.array_init_fn import u8f
from cp_library.ds.elist_fn import elist
from math import gcd
'''
╺━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸
https://kobejean.github.io/cp-library
'''
from typing import Iterable
import typing
from collections import deque
from numbers import Number
from types import GenericAlias
from typing import Callable, Collection, Iterator, Union
import os
import sys
from io import BytesIO, IOBase
class FastIO(IOBase):
BUFSIZE = 8192
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
BUFSIZE = self.BUFSIZE
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
BUFSIZE = self.BUFSIZE
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
stdin: 'IOWrapper' = None
stdout: 'IOWrapper' = None
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
def write(self, s):
return self.buffer.write(s.encode("ascii"))
def read(self):
return self.buffer.read().decode("ascii")
def readline(self):
return self.buffer.readline().decode("ascii")
sys.stdin = IOWrapper.stdin = IOWrapper(sys.stdin)
sys.stdout = IOWrapper.stdout = IOWrapper(sys.stdout)
from typing import TypeVar
_T = TypeVar('T')
class TokenStream(Iterator):
stream = IOWrapper.stdin
def __init__(self):
self.queue = deque()
def __next__(self):
if not self.queue: self.queue.extend(self._line())
return self.queue.popleft()
def wait(self):
if not self.queue: self.queue.extend(self._line())
while self.queue: yield
def _line(self):
return TokenStream.stream.readline().split()
def line(self):
if self.queue:
A = list(self.queue)
self.queue.clear()
return A
return self._line()
TokenStream.default = TokenStream()
class CharStream(TokenStream):
def _line(self):
return TokenStream.stream.readline().rstrip()
CharStream.default = CharStream()
ParseFn = Callable[[TokenStream],_T]
class Parser:
def __init__(self, spec: Union[type[_T],_T]):
self.parse = Parser.compile(spec)
def __call__(self, ts: TokenStream) -> _T:
return self.parse(ts)
@staticmethod
def compile_type(cls: type[_T], args = ()) -> _T:
if issubclass(cls, Parsable):
return cls.compile(*args)
elif issubclass(cls, (Number, str)):
def parse(ts: TokenStream): return cls(next(ts))
return parse
elif issubclass(cls, tuple):
return Parser.compile_tuple(cls, args)
elif issubclass(cls, Collection):
return Parser.compile_collection(cls, args)
elif callable(cls):
def parse(ts: TokenStream):
return cls(next(ts))
return parse
else:
raise NotImplementedError()
@staticmethod
def compile(spec: Union[type[_T],_T]=int) -> ParseFn[_T]:
if isinstance(spec, (type, GenericAlias)):
cls = typing.get_origin(spec) or spec
args = typing.get_args(spec) or tuple()
return Parser.compile_type(cls, args)
elif isinstance(offset := spec, Number):
cls = type(spec)
def parse(ts: TokenStream): return cls(next(ts)) + offset
return parse
elif isinstance(args := spec, tuple):
return Parser.compile_tuple(type(spec), args)
elif isinstance(args := spec, Collection):
return Parser.compile_collection(type(spec), args)
elif isinstance(fn := spec, Callable):
def parse(ts: TokenStream): return fn(next(ts))
return parse
else:
raise NotImplementedError()
@staticmethod
def compile_line(cls: _T, spec=int) -> ParseFn[_T]:
if spec is int:
fn = Parser.compile(spec)
def parse(ts: TokenStream): return cls([int(token) for token in ts.line()])
return parse
else:
fn = Parser.compile(spec)
def parse(ts: TokenStream): return cls([fn(ts) for _ in ts.wait()])
return parse
@staticmethod
def compile_repeat(cls: _T, spec, N) -> ParseFn[_T]:
fn = Parser.compile(spec)
def parse(ts: TokenStream): return cls([fn(ts) for _ in range(N)])
return parse
@staticmethod
def compile_children(cls: _T, specs) -> ParseFn[_T]:
fns = tuple((Parser.compile(spec) for spec in specs))
def parse(ts: TokenStream): return cls([fn(ts) for fn in fns])
return parse
@staticmethod
def compile_tuple(cls: type[_T], specs) -> ParseFn[_T]:
if isinstance(specs, (tuple,list)) and len(specs) == 2 and specs[1] is ...:
return Parser.compile_line(cls, specs[0])
else:
return Parser.compile_children(cls, specs)
@staticmethod
def compile_collection(cls, specs):
if not specs or len(specs) == 1 or isinstance(specs, set):
return Parser.compile_line(cls, *specs)
elif (isinstance(specs, (tuple,list)) and len(specs) == 2 and isinstance(specs[1], int)):
return Parser.compile_repeat(cls, specs[0], specs[1])
else:
raise NotImplementedError()
class Parsable:
@classmethod
def compile(cls):
def parser(ts: TokenStream): return cls(next(ts))
return parser
class FuncGraph(list[int], Parsable):
def __init__(F, successors):
super().__init__(successors)
F.N = F.M = len(F)
def find_cycle(P, root: int) -> list[int]:
slow = fast = root
while (slow := P[slow]) != (fast := P[P[fast]]): pass
cyc = [slow]
while P[slow] != fast: cyc.append(slow := P[slow])
return cyc
def cycles(P) -> 'CRFList[int]':
vis, cycs, S = u8f(N := P.N), elist(N), elist(N)
for v in range(P.N):
if vis[v]: continue
slow = fast = v
while (slow := P[slow]) != (fast := P[P[fast]]) and not vis[fast]: pass
if vis[fast]: continue
S.append(len(cycs))
cycs.append(slow)
vis[slow := P[slow]] = 1
while slow != fast:
cycs.append(slow)
vis[slow := P[slow]] = 1
return CRFList(cycs, S)
def chain(P, root):
cyc = P.find_cycle(root)
slow, fast = root, cyc[0]
if slow == fast: return [], cyc
line = [slow]
while (slow := P[slow]) != (fast := P[fast]):
line.append(slow)
return line, roll(cyc, -cyc.index(slow))
@classmethod
def compile(cls, N: int, shift = -1):
return Parser.compile_repeat(cls, shift, N)
from typing import Generic
class CRFList(Generic[_T]):
def __init__(crf, A: list[_T], S: list[int]):
crf.N, crf.A, crf.S = len(S), A, S
S.append(len(A))
def __len__(crf) -> int: return crf.N
def __getitem__(crf, i: int) -> list[_T]:
return crf.A[crf.S[i]:crf.S[i+1]]
def get(crf, i: int, j: int) -> _T:
return crf.A[crf.S[i]+j]
def len(crf, i: int) -> int:
return crf.S[i+1] - crf.S[i]
def roll(A: list, t: int):
if t:=t%len(A): A[:t], A[t:] = A[-t:], A[:-t]
return A
from array import array
def i8f(N: int, elm: int = 0): return array('b', (elm,))*N # signed char
def u8f(N: int, elm: int = 0): return array('B', (elm,))*N # unsigned char
def i16f(N: int, elm: int = 0): return array('h', (elm,))*N # signed short
def u16f(N: int, elm: int = 0): return array('H', (elm,))*N # unsigned short
def i32f(N: int, elm: int = 0): return array('i', (elm,))*N # signed int
def u32f(N: int, elm: int = 0): return array('I', (elm,))*N # unsigned int
def i64f(N: int, elm: int = 0): return array('q', (elm,))*N # signed long long
# def u64f(N: int, elm: int = 0): return array('Q', (elm,))*N # unsigned long long
def f32f(N: int, elm: float = 0.0): return array('f', (elm,))*N # float
def f64f(N: int, elm: float = 0.0): return array('d', (elm,))*N # double
def i8a(init = None): return array('b') if init is None else array('b', init) # signed char
def u8a(init = None): return array('B') if init is None else array('B', init) # unsigned char
def i16a(init = None): return array('h') if init is None else array('h', init) # signed short
def u16a(init = None): return array('H') if init is None else array('H', init) # unsigned short
def i32a(init = None): return array('i') if init is None else array('i', init) # signed int
def u32a(init = None): return array('I') if init is None else array('I', init) # unsigned int
def i64a(init = None): return array('q') if init is None else array('q', init) # signed long long
# def u64a(init = None): return array('Q') if init is None else array('Q', init) # unsigned long long
def f32a(init = None): return array('f') if init is None else array('f', init) # float
def f64a(init = None): return array('d') if init is None else array('d', init) # double
i8_max = (1 << 7)-1
u8_max = (1 << 8)-1
i16_max = (1 << 15)-1
u16_max = (1 << 16)-1
i32_max = (1 << 31)-1
u32_max = (1 << 32)-1
i64_max = (1 << 63)-1
u64_max = (1 << 64)-1
def elist(est_len: int) -> list: ...
try:
from __pypy__ import newlist_hint
except:
def newlist_hint(hint):
return []
elist = newlist_hint