id
stringlengths
24
27
content
stringlengths
37
384k
max_stars_repo_path
stringlengths
51
51
condefects-python_data_2501
s = input() if s.islower(): print("No") exit() for i in range(1, len(s) - 1): if s[i].isupper(): print("No") exit() print("Yes") s = input() if s.islower(): print("No") exit() for i in range(1, len(s)): if s[i].isupper(): print("No") exit() print("Yes")
ConDefects/ConDefects/Code/abc338_a/Python/54889106
condefects-python_data_2502
S = input() C = S[0] D = S[1:] ans = True if C.isupper() and D.islower() or len(S) == 1: print("Yes") else: print("No") S = input() C = S[0] D = S[1:] ans = True if C.isupper() and (len(S) == 1 or D.islower()): print("Yes") else: print("No")
ConDefects/ConDefects/Code/abc338_a/Python/54630438
condefects-python_data_2503
S = input() if S[0].isupper(): if (len(S)>= 2 and S[1:].islower()) or len(S) == 1: print("Yes") else: print("No") S = input() if S[0].isupper(): if (len(S)>= 2 and S[1:].islower()) or len(S) == 1: print("Yes") else: print("No") else: print("No")
ConDefects/ConDefects/Code/abc338_a/Python/55016820
condefects-python_data_2504
def remove_str(input_str): result = input_str.replace('a', '').replace('e', '').replace('o', '') return result s = input() s_result = remove_str(s) print(s_result) def remove_str(input_str): result = input_str.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '') return result s = input() s_result = remove_str(s) print(s_result)
ConDefects/ConDefects/Code/abc315_a/Python/46129092
condefects-python_data_2505
S = input() List = list(S) result = [i for i in List if i != 'a' and i != 'i' and i != 'u' and i != 'e' and i != 'o'] print(result) S = input() List = list(S) result = [i for i in List if i != 'a' and i != 'i' and i != 'u' and i != 'e' and i != 'o'] print(''.join(result))
ConDefects/ConDefects/Code/abc315_a/Python/46159521
condefects-python_data_2506
import re re.sub("a|e|i|o|u", "", input()) import re print(re.sub("a|e|i|o|u", "", input()))
ConDefects/ConDefects/Code/abc315_a/Python/46219249
condefects-python_data_2507
from collections import defaultdict H, W = map(int, input().split()) C = [list(input()) for _ in range(H)] G = defaultdict(list) for i in range(H): for j in range(W): if C[i][j] == "." and i + 1 <= H - 1: if C[i + 1][j] == ".": G[(i, j)].append((i + 1, j)) if C[i][j] == "." and j + 1 <= W - 1: if C[i][j + 1] == ".": G[(i, j)].append((i, j + 1)) visited = set() def dfs(p): global visited visited.add(p) for next in G[p]: if next not in visited: dfs(next) dfs((0, 0)) ans = 0 for v in visited: ans = max(ans, v[0] + v[1]) print(ans) from collections import defaultdict H, W = map(int, input().split()) C = [list(input()) for _ in range(H)] G = defaultdict(list) for i in range(H): for j in range(W): if C[i][j] == "." and i + 1 <= H - 1: if C[i + 1][j] == ".": G[(i, j)].append((i + 1, j)) if C[i][j] == "." and j + 1 <= W - 1: if C[i][j + 1] == ".": G[(i, j)].append((i, j + 1)) visited = set() def dfs(p): global visited visited.add(p) for next in G[p]: if next not in visited: dfs(next) dfs((0, 0)) ans = 0 for v in visited: ans = max(ans, v[0] + v[1] + 1) print(ans)
ConDefects/ConDefects/Code/abc232_d/Python/45343318
condefects-python_data_2508
h, w = map(int, input().split()) c = [input() for i in range(h)] s = [[0] * w for i in range(h)] s[0][0] = 1 ans = 1 for i in range(h): for j in range(w): if c[i][j] == '#' or i == j == 0: continue if i == 0 and j > 0: s[i][j] = s[i][j-1]+1 elif i > 0 and j == 0: s[i][j] = s[i-1][j]+1 else: s[i][j] = max(s[i][j-1], s[i-1][j])+1 if s[i][j] == 1: s[i][j] == 0 if ans < s[i][j]: ans = s[i][j] print(ans) h, w = map(int, input().split()) c = [input() for i in range(h)] s = [[0] * w for i in range(h)] s[0][0] = 1 ans = 1 for i in range(h): for j in range(w): if c[i][j] == '#' or i == j == 0: continue if i == 0 and j > 0: s[i][j] = s[i][j-1]+1 elif i > 0 and j == 0: s[i][j] = s[i-1][j]+1 else: s[i][j] = max(s[i][j-1], s[i-1][j])+1 if s[i][j] == 1: s[i][j] = 0 if ans < s[i][j]: ans = s[i][j] print(ans)
ConDefects/ConDefects/Code/abc232_d/Python/44805380
condefects-python_data_2509
# -*- coding: utf-8 -*- def main(): import sys from collections import deque from typing import Any, List, Tuple input = sys.stdin.readline h, w = map(int, input().split()) c = [list(input().rstrip()) for _ in range(h)] sy, sx = 0, 0 def bfs_for_grid( grid: List[List[Any]], h: int, w: int, sy: int = 0, sx: int = 0 ) -> Tuple[List[List[bool]], List[List[int]]]: d = deque() d.append((sy, sx)) visited = [[False] * w for _ in range(h)] pending = -1 dist = [[pending] * w for _ in range(h)] dist[sy][sx] = 1 # Initialize dxy = [(-1, 0), (1, 0), (0, -1), (0, 1)] while d: y, x = d.popleft() if dist[y][x] == pending: continue if visited[y][x]: continue visited[y][x] = True for dx, dy in dxy: nx = x + dx ny = y + dy if nx < 0 or nx >= w or ny < 0 or ny >= h: continue if visited[ny][nx]: continue if grid[ny][nx] == "#": continue if dist[ny][nx] != pending and dist[ny][nx] <= dist[y][x]: continue dist[ny][nx] = dist[y][x] + 1 # Update ans d.append((ny, nx)) return visited, dist visited, dist = bfs_for_grid(grid=c, h=h, w=w, sy=sy, sx=sx) # print(dist) ans = 1 for i in range(h): for j in range(w): ans = max(ans, dist[i][j]) print(ans) if __name__ == "__main__": main() # -*- coding: utf-8 -*- def main(): import sys from collections import deque from typing import Any, List, Tuple input = sys.stdin.readline h, w = map(int, input().split()) c = [list(input().rstrip()) for _ in range(h)] sy, sx = 0, 0 def bfs_for_grid( grid: List[List[Any]], h: int, w: int, sy: int = 0, sx: int = 0 ) -> Tuple[List[List[bool]], List[List[int]]]: d = deque() d.append((sy, sx)) visited = [[False] * w for _ in range(h)] pending = -1 dist = [[pending] * w for _ in range(h)] dist[sy][sx] = 1 # Initialize dxy = [(1, 0), (0, 1)] while d: y, x = d.popleft() if dist[y][x] == pending: continue if visited[y][x]: continue visited[y][x] = True for dx, dy in dxy: nx = x + dx ny = y + dy if nx < 0 or nx >= w or ny < 0 or ny >= h: continue if visited[ny][nx]: continue if grid[ny][nx] == "#": continue if dist[ny][nx] != pending and dist[ny][nx] <= dist[y][x]: continue dist[ny][nx] = dist[y][x] + 1 # Update ans d.append((ny, nx)) return visited, dist visited, dist = bfs_for_grid(grid=c, h=h, w=w, sy=sy, sx=sx) # print(dist) ans = 1 for i in range(h): for j in range(w): ans = max(ans, dist[i][j]) print(ans) if __name__ == "__main__": main()
ConDefects/ConDefects/Code/abc232_d/Python/45267327
condefects-python_data_2510
from collections import deque h,w = map(int, input().split()) mp = [list(input()) for i in range(h)] Q = deque() root = [[-1]* w for i in range(h)] dist = [(0, 1), (0, -1), (1, 0), (-1, 0)] cnt = 0 Q.append((0,0)) root[0][0] = 0 while Q: y, x = Q.popleft() for dy, dx in dist: y2 = y + dy x2 = x + dx if not (0 <= y2 < h and 0 <= x2 < w): continue if mp[y2][x2] == "#": continue if root[y2][x2] == -1: root[y2][x2] = root[y][x] + 1 Q.append([y2, x2]) ans = sum(root,[]) print(max(ans) + 1) from collections import deque h,w = map(int, input().split()) mp = [list(input()) for i in range(h)] Q = deque() root = [[-1]* w for i in range(h)] dist = [(0, 1),(1, 0)] cnt = 0 Q.append((0,0)) root[0][0] = 0 while Q: y, x = Q.popleft() for dy, dx in dist: y2 = y + dy x2 = x + dx if not (0 <= y2 < h and 0 <= x2 < w): continue if mp[y2][x2] == "#": continue if root[y2][x2] == -1: root[y2][x2] = root[y][x] + 1 Q.append([y2, x2]) ans = sum(root,[]) print(max(ans) + 1)
ConDefects/ConDefects/Code/abc232_d/Python/45068396
condefects-python_data_2511
# import pypyjit;pypyjit.set_param("max_unroll_recursion=-1") # from bisect import * # from collections import * # from heapq import * # from itertools import * # from math import * # from datetime import * # from decimal import * # PyPyだと遅い # from string import ascii_lowercase,ascii_uppercase # import numpy as np import sys # sys.setrecursionlimit(10**6) # PyPyだと遅い INF = 1 << 61 MOD = 998244353 # MOD = 10**9 + 7 File = sys.stdin def input(): return File.readline()[:-1] # /////////////////////////////////////////////////////////////////////////// H, W = map(int, input().split()) C = [list(input()) for _ in range(H)] dp = [[0] * W for _ in range(H)] dp[0][0] = 1 for i in range(H): for j in range(W): if j < W - 1 and C[i][j + 1] == ".": dp[i][j + 1] = max(dp[i][j + 1], dp[i][j] + 1) if i < H - 1 and C[i + 1][j] == ".": dp[i + 1][j] = max(dp[i + 1][j], dp[i][j] + 1) ans = 0 for i in range(H): for j in range(W): ans = max(ans, dp[i][j]) print(ans) # import pypyjit;pypyjit.set_param("max_unroll_recursion=-1") # from bisect import * # from collections import * # from heapq import * # from itertools import * # from math import * # from datetime import * # from decimal import * # PyPyだと遅い # from string import ascii_lowercase,ascii_uppercase # import numpy as np import sys # sys.setrecursionlimit(10**6) # PyPyだと遅い INF = 1 << 61 MOD = 998244353 # MOD = 10**9 + 7 File = sys.stdin def input(): return File.readline()[:-1] # /////////////////////////////////////////////////////////////////////////// H, W = map(int, input().split()) C = [list(input()) for _ in range(H)] dp = [[0] * W for _ in range(H)] dp[0][0] = 1 for i in range(H): for j in range(W): if dp[i][j] == 0: continue if j < W - 1 and C[i][j + 1] == ".": dp[i][j + 1] = max(dp[i][j + 1], dp[i][j] + 1) if i < H - 1 and C[i + 1][j] == ".": dp[i + 1][j] = max(dp[i + 1][j], dp[i][j] + 1) ans = 0 for i in range(H): for j in range(W): ans = max(ans, dp[i][j]) print(ans)
ConDefects/ConDefects/Code/abc232_d/Python/45266728
condefects-python_data_2512
H,W=map(int,input().split()) dp=[[-10**10]*W for i in range(H)] S=[input() for i in range(H)] dp[0][0]=1 for i in range(H): for j in range(W): if S[i][j]=='.': dp[i][j]=max(dp[i][j],dp[i-1][j]+1,dp[i][j-1]+1) result=0 for i in range(H): w=max(dp[i]) result=max(result,w) print(result) H,W=map(int,input().split()) dp=[[-10**10]*W for i in range(H)] S=[input() for i in range(H)] dp[0][0]=1 for i in range(H): for j in range(W): if i==0 and j==0: continue if S[i][j]=='.': dp[i][j]=max(dp[i][j],dp[i-1][j]+1,dp[i][j-1]+1) result=0 for i in range(H): w=max(dp[i]) result=max(result,w) print(result)
ConDefects/ConDefects/Code/abc232_d/Python/45266729
condefects-python_data_2513
from collections import deque H,W = map(int,input().split()) C = [input() for _ in range(H)] dxs = [0,1] dys = [1,0] que = deque() que.append((0,0)) dis = [[-1]*W for _ in range(H)] dis[0][0]=1 ans = 0 while que: y,x = que.popleft() for dy,dx in zip(dys,dxs): ny = y+dy nx = x+dx if ny>=H or nx>=W: continue if C[ny][nx]=='.' and dis[ny][nx]==-1: dis[ny][nx]=dis[y][x]+1 ans = max(ans,dis[ny][nx]) que.append((ny,nx)) print(ans) from collections import deque H,W = map(int,input().split()) C = [input() for _ in range(H)] dxs = [0,1] dys = [1,0] que = deque() que.append((0,0)) dis = [[-1]*W for _ in range(H)] dis[0][0]=1 ans = 1 while que: y,x = que.popleft() for dy,dx in zip(dys,dxs): ny = y+dy nx = x+dx if ny>=H or nx>=W: continue if C[ny][nx]=='.' and dis[ny][nx]==-1: dis[ny][nx]=dis[y][x]+1 ans = max(ans,dis[ny][nx]) que.append((ny,nx)) print(ans)
ConDefects/ConDefects/Code/abc232_d/Python/45499422
condefects-python_data_2514
N, M = map(int, input().split()) p = list(map(int, input().split())) if M > 0 else [] graph = "" for i in range(1, N+1): node = str(i) graph += node + ("v" if i in p else ",") result = [] for subgraph in graph.split(","): result += sorted(subgraph.split("v"), reverse=True) print(*result) N, M = map(int, input().split()) p = list(map(int, input().split())) if M > 0 else [] graph = "" for i in range(1, N+1): node = str(i) graph += node + ("v" if i in p else ",") result = [] for subgraph in graph.split(","): result += sorted(list(map(int, subgraph.split("v"))), reverse=True) if len(subgraph) > 0 else [] print(*result)
ConDefects/ConDefects/Code/abc289_b/Python/44836694
condefects-python_data_2515
# InlineImporter import os as _os import sys as _sys from functools import lru_cache as _lru_cache from importlib.abc import ExecutionLoader, MetaPathFinder from importlib.machinery import ModuleSpec class InlineImporter(ExecutionLoader, MetaPathFinder): version = None inlined_modules = {} namespace_packages = False @classmethod def find_spec(cls, fullname, path=None, target=None): """Find a spec for a given module. Because we only deal with our inlined module, we don't have to care about path or target. The import machinery also takes care of fully resolving all names, so we just have to deal with the fullnames. """ if fullname in cls.inlined_modules: # We have inlined this module, so return the spec ms = ModuleSpec(fullname, cls, origin=cls.get_filename(fullname), is_package=cls.is_package(fullname)) ms.has_location = True if cls.namespace_packages and ms.submodule_search_locations is not None: for p in _sys.path: ms.submodule_search_locations.append(_os.path.join(p, _os.path.dirname(ms.origin))) return ms return None @staticmethod def _call_with_frames_removed(f, *args, **kwds): """remove_importlib_frames in import.c will always remove sequences of importlib frames that end with a call to this function Use it instead of a normal call in places where including the importlib frames introduces unwanted noise into the traceback (e.g. when executing module code) """ return f(*args, **kwds) @classmethod def create_module(cls, spec): """Create a module using the default machinery.""" return None @classmethod def exec_module(cls, module): """Execute the module.""" code = cls.get_code(module.__name__) if code is None: raise ImportError("cannot load module {!r} when get_code() returns None".format(module.__name__)) cls._call_with_frames_removed(exec, code, module.__dict__) @classmethod @_lru_cache(maxsize=None) def get_filename(cls, fullname): """Returns the Raises ImportError if the module cannot be found. """ if fullname not in cls.inlined_modules: raise ImportError mod = cls.inlined_modules[fullname] origin = fullname if mod[0]: origin = ".".join([origin, "__init__"]) origin = ".".join([origin.replace(".", "/"), "py"]) return origin @classmethod @_lru_cache(maxsize=None) def is_package(cls, fullname): if fullname not in cls.inlined_modules: raise ImportError return cls.inlined_modules[fullname][0] @classmethod def get_source(cls, fullname): if fullname not in cls.inlined_modules: raise ImportError return cls.inlined_modules[fullname][1] @classmethod def get_code(cls, fullname): """Method to return the code object for fullname. Should return None if not applicable (e.g. built-in module). Raise ImportError if the module cannot be found. """ source = cls.get_source(fullname) if source is None: return None try: path = cls.get_filename(fullname) except ImportError: return cls.source_to_code(source) else: return cls.source_to_code(source, path) InlineImporter.version = '0.0.4' InlineImporter.inlined_modules = { 'lib.array2d': (False, "class Array2dView:\n def __init__(self, arr, i_indices, j_indices):\n self.arr = arr\n self.i_indices = i_indices\n self.j_indices = j_indices\n self.n = len(i_indices)\n self.m = len(j_indices)\n \n def _get_view(self, i, j):\n i = self.i_indices[i]\n j = self.j_indices[j]\n return Array2dView(self.arr, i, j)\n\n def get_ind(self, i, j):\n return self.i_indices[i]+self.j_indices[j]\n \n def __getitem__(self, index):\n i, j = index\n try:\n return self.arr[self.get_ind(i,j)]\n except TypeError:\n return self._get_view(i, j)\n \n def __setitem__(self, index, value):\n i, j = index\n try:\n self.arr[self.get_ind(i,j)] = value\n except TypeError:\n x = self._get_view(i, j)\n for i in x.i_indices:\n for j in x.j_indices:\n self.arr[i+j] = value\n \n def __iter__(self):\n for i in self.i_indices:\n for j in self.j_indices:\n yield self.arr[i+j]\n \n def __reversed__(self):\n for i in reversed(self.i_indices):\n for j in reversed(self.j_indices):\n yield self.arr[i+j]\n \n def __str__(self):\n m = max(len(str(v)) for v in self)\n res = ['']*len(self.i_indices)\n row = ['']*(len(self.j_indices)+2)\n for ri,i in enumerate(self.i_indices):\n if ri == 0:\n row[0] = '['\n else:\n row[0] = ' '\n if ri == len(self.i_indices)-1:\n row[-1] = ']\\n'\n for rj,j in enumerate(self.j_indices):\n row[rj+1] = f'{str(self.arr[i+j]):>{m+1}}'\n res[ri] = ''.join(row)\n return '\\n'.join(res)\n \n def copy(self):\n return Array2d(len(self.i_indices), len(self.j_indices), list(self))\n\n\nclass Array2d:\n def __init__(self, n, m, arr):\n self.n = n\n self.m = m\n self.arr = arr\n \n @classmethod\n def full(cls, n, m, fill_value):\n return cls(n, m, [fill_value]*(n*m))\n \n @classmethod\n def from_list(cls, lst):\n n,m = len(lst), len(lst[0])\n arr = [lst[0]]*(n*m)\n k = 0\n for row in lst:\n for v in row:\n arr[k] = v\n k += 1\n return cls(n, m, arr)\n \n def _get_view(self, i, j):\n i = tuple(range(0, self.n*self.m, self.m))[i]\n j = tuple(range(self.m))[j]\n return Array2dView(self.arr, i, j)\n\n def get_ind(self, i, j):\n return i*self.m+j\n\n def __getitem__(self, index):\n try:\n return self.arr[self.get_ind(*index)]\n except TypeError:\n return self._get_view(*index)\n \n def __setitem__(self, index, value):\n try:\n self.arr[self.get_ind(*index)] = value\n except TypeError:\n x = self._get_view(*index)\n for i in x.i_indices:\n for j in x.j_indices:\n self.arr[i+j] = value\n \n def __iter__(self):\n return iter(self.arr)\n \n def __reversed__(self):\n return reversed(self.arr)\n \n def __str__(self):\n m = max(len(str(v)) for v in self)\n res = ['']*self.n\n row = ['']*(self.m+2)\n for i in range(self.n):\n if i == 0:\n row[0] = '['\n else:\n row[0] = ' '\n if i == self.n-1:\n row[-1] = ']\\n'\n for j in range(self.m):\n row[j+1] = f'{str(self.arr[i*self.m+j]):>{m+1}}'\n res[i] = ''.join(row)\n return '\\n'.join(res)\n\n __repr__ = __str__\n\n def __eq__(self, other):\n return self.arr == other.arr\n\n def copy(self):\n return self.__class__(self.n, self.m, self.arr[:])\n\n @property\n def t(self):\n arr = [self.arr[0]]*(len(self.arr))\n x = 0\n for i in range(self.n):\n for j in range(self.m):\n arr[j*self.n + i] = self.arr[x]\n x += 1\n return self.__class__(self.m, self.n, arr)\n"), 'lib.array3d': (False, 'class Array3d(list):\n def __init__(self, n, m, p, arr):\n list.__init__(self, arr)\n self.n = n\n self.m = m\n self.p = p\n self.mp = m*p\n\n @classmethod\n def full(cls, n, m, p, fill_value):\n return cls(n, m, p, [fill_value] * (n * m * p))\n\n def get_ind(self, i, j, k):\n return i * self.mp + j * self.p + k\n\n def __getitem__(self, index):\n return list.__getitem__(self, self.get_ind(*index))\n\n def __setitem__(self, index, value):\n list.__setitem__(self, self.get_ind(*index), value)\n'), 'lib.benchmark': (False, '\nfrom time import perf_counter as timer\ndef simple_timeit(func, repeat=1000, warmup=100):\n for i in range(warmup):\n func(i)\n start = timer()\n for i in range(repeat):\n func(i)\n stop = timer()\n return stop-start\n'), 'lib.data_structure': (False, 'from typing import List, Any, TypeVar, Iterator\nfrom collections.abc import MutableSet\n\nclass DisjointSet:\n def __init__(self, parent):\n self.parent = parent\n\n @classmethod\n def empty(cls, size):\n return cls([-1]*size)\n\n def find(self, x):\n stack = []\n while self.parent[x] >= 0:\n stack.append(x)\n x = self.parent[x]\n for y in stack:\n self.parent[y] = x\n return x\n\n def union_reps(self, xr, yr):\n if xr == yr:\n return xr\n if self.parent[xr] > self.parent[yr]:\n xr, yr = yr, xr\n self.parent[xr] += self.parent[yr]\n self.parent[yr] = xr\n return xr\n\n def union(self, x, y):\n return self.union_reps(self.find(x), self.find(y))\n\n def group_size(self, x):\n return -self.parent[self.find(x)]\n\n def is_rep(self, x):\n return self.parent[x] < 0\n\n def copy(self):\n return DisjointSet(self.parent)\n\n\nclass SegmentTree:\n """\n ???????????????????????????????????\n ???????????????????????????(???????????)\n """\n\n @classmethod\n def all_identity(cls, operator, identity, size):\n return cls(operator, identity, [identity] * (2 << (size - 1).bit_length()))\n\n @classmethod\n def from_initial_data(cls, operator, identity, data):\n size = 1 << (len(data) - 1).bit_length()\n temp = [identity] * (2 * size)\n temp[size:size + len(data)] = data\n data = temp\n\n for i in reversed(range(size)):\n data[i] = operator(data[2 * i], data[2 * i + 1])\n return cls(operator, identity, data)\n\n # ??????????????????????\n def __init__(self, operator, identity, data):\n self.op = operator\n self.id = identity\n self.data = data\n self.size = len(data) // 2\n\n def reduce(self, l, r):\n l += self.size\n r += self.size\n vl = self.id\n vr = self.id\n\n while l < r:\n if l & 1:\n vl = self.op(vl, self.data[l])\n l += 1\n if r & 1:\n r -= 1\n vr = self.op(self.data[r], vr)\n l >>= 1\n r >>= 1\n return self.op(vl, vr)\n\n def elements(self, l, r):\n l += self.size\n r += self.size\n\n lefts = []\n rights = []\n\n while l < r:\n if l & 1:\n lefts.append(self.data[l])\n l += 1\n if r & 1:\n r -= 1\n rights.append(self.data[r])\n l >>= 1\n r >>= 1\n return lefts, rights\n\n def __getitem__(self, i):\n if isinstance(i, slice):\n return self.reduce(\n 0 if i.start is None else i.start,\n self.size if i.stop is None else i.stop)\n elif isinstance(i, int):\n return self.data[i + self.size]\n\n def __setitem__(self, i, v):\n i += self.size\n while i:\n self.data[i] = v\n v = self.op(self.data[i ^ 1], v) if i & 1 else self.op(v, self.data[i ^ 1])\n i >>= 1\n\n def __iter__(self):\n return iter(self.data[self.size:])\n\n\nclass LazySegmentTree:\n """\n op: ????????reduce?????????\n apply: ??????\n comp: ??????\n \n range_query: reduce(op, (apply(x,m) for x,m in zip(X,M)))\n \n ???????:\n \n ??X (??)\n op[+]: X,X -> X\n (X, op)?????\n \n ??M (???)\n comp[*]: M,M -> M\n (M, compose)?????\n \n apply[f(x,m,n)]: X,M,Z+ -> X\n (Z+????)\n \n f(x,e_M,n) = x\n f(x,m*n,p) = f(f(x,m,p),n,p)\n f(x,m,p)+f(y,m,q) = f(x+y,m,p+q)\n \n ??: https://algo-logic.info/segment-tree/#toc_id_3\n """\n\n @classmethod\n def all_identity(cls, op, op_e, comp, comp_e, apply, size):\n size = 1 << (size - 1).bit_length()\n return cls(\n op,\n op_e,\n comp,\n comp_e,\n apply,\n [op_e] * (2 * size),\n [comp_e] * size\n )\n\n @classmethod\n def from_initial_data(cls, op, op_e, comp, comp_e, apply, data):\n size = 1 << (len(data) - 1).bit_length()\n temp = [op_e] * (2 * size)\n temp[size:size + len(data)] = data\n\n for i in reversed(range(size)):\n temp[i] = op(temp[2 * i], temp[2 * i + 1])\n return cls(\n op,\n op_e,\n comp,\n comp_e,\n apply,\n temp,\n [comp_e] * size\n )\n\n # ??????????????????????\n def __init__(self, op, op_e, comp, comp_e, apply, data, lazy):\n self.op = op\n self.op_e = op_e\n self.comp = comp\n self.comp_e = comp_e\n self.apply = apply\n self.data = data\n self.lazy = lazy\n self.size = len(self.data) // 2\n self.depth = self.size.bit_length() - 1\n self._l_indices = [0] * self.depth\n self._r_indices = [0] * self.depth\n\n def _update_indices(self, i, l):\n m = i // (i & -i)\n i >>= 1\n for k in range(self.depth):\n l[k] = i if i < m else 0\n i >>= 1\n\n def _propagate_top_down(self):\n data = self.data\n lazy = self.lazy\n apply = self.apply\n comp = self.comp\n comp_e = self.comp_e\n k = self.size >> 1\n\n for i, j in zip(reversed(self._l_indices), reversed(self._r_indices)):\n if i > 0:\n temp = lazy[i]\n if temp != comp_e:\n lazy[i] = comp_e\n a = i << 1\n b = a | 1\n data[a] = apply(data[a], temp, k)\n data[b] = apply(data[b], temp, k)\n if k > 1:\n lazy[a] = comp(lazy[a], temp)\n lazy[b] = comp(lazy[b], temp)\n if i < j:\n temp = lazy[j]\n if temp != comp_e:\n lazy[j] = comp_e\n a = j << 1\n b = a | 1\n data[a] = apply(data[a], temp, k)\n data[b] = apply(data[b], temp, k)\n if k > 1:\n lazy[a] = comp(lazy[a], temp)\n lazy[b] = comp(lazy[b], temp)\n k >>= 1\n\n def _propagate_bottom_up(self):\n data = self.data\n op = self.op\n for i, j in zip(self._l_indices, self._r_indices):\n if i < j:\n data[j] = op(data[j << 1], data[j << 1 | 1])\n if i > 0:\n data[i] = op(data[i << 1], data[i << 1 | 1])\n\n def update_interval(self, l, r, m):\n lazy = self.lazy\n data = self.data\n comp = self.comp\n apply = self.apply\n\n l += self.size\n r += self.size\n self._update_indices(l, self._l_indices)\n self._update_indices(r, self._r_indices)\n self._propagate_top_down()\n k = 1\n while l < r:\n if l & 1:\n data[l] = apply(data[l], m, k)\n if k > 1:\n lazy[l] = comp(lazy[l], m)\n l += 1\n if r & 1:\n r -= 1\n data[r] = apply(data[r], m, k)\n if k > 1:\n lazy[r] = comp(lazy[r], m)\n l >>= 1\n r >>= 1\n k <<= 1\n self._propagate_bottom_up()\n\n def get_interval(self, l, r):\n data = self.data\n op = self.op\n\n l += self.size\n r += self.size\n self._update_indices(l, self._l_indices)\n self._update_indices(r, self._r_indices)\n self._propagate_top_down()\n\n lx = self.op_e\n rx = self.op_e\n while l < r:\n if l & 1:\n lx = op(lx, data[l])\n l += 1\n if r & 1:\n r -= 1\n rx = op(data[r], rx)\n l >>= 1\n r >>= 1\n return op(lx, rx)\n\n\nfrom operator import add, sub\n\n\nclass BinaryIndexedTree:\n def __init__(self, size, zero=0, operator=add, inv_operator=sub):\n self.zero = zero\n self.op = operator\n self.inv = inv_operator\n self.data = [zero] * (size + 1)\n self.msb = 1 << (size.bit_length() - 1)\n\n def _add(self, i, w):\n i += 1\n while i < len(self.data):\n self.data[i] = self.op(self.data[i], w)\n i += i & -i\n\n def _get_sum(self, i):\n res = self.zero\n while i > 0:\n res = self.op(res, self.data[i])\n i -= i & -i\n return res\n\n def __getitem__(self, i):\n """\n [0,i)\n """\n if isinstance(i, slice):\n a = self._get_sum(len(self.data) - 1 if i.stop is None else i.stop)\n b = self._get_sum(0 if i.start is None else i.start)\n return self.inv(a, b)\n else:\n return self.zero # fake value\n\n __setitem__ = _add\n\n def bisect_left(self, v):\n """\n return smallest i s.t v <= sum[:i+1]\n """\n i = 0\n k = self.msb\n l = len(self.data)\n while k > 0:\n i += k\n if i < l and self.data[i] < v:\n v -= self.data[i]\n else:\n i -= k\n k >>= 1\n return i\n\n def bisect_right(self, v):\n """\n return smallest i s.t v < sum[:i+1]\n """\n i = 0\n k = self.msb\n l = len(self.data)\n while k > 0:\n i += k\n if i < l and self.data[i] <= v:\n v -= self.data[i]\n else:\n i -= k\n k >>= 1\n return i\n\n bisect = bisect_right\n\n\nimport bisect\nT = TypeVar(\'T\')\n\n\nclass SortedList(MutableSet):\n\n def __init__(self, sorted_values: List[T]):\n self.i2v = sorted_values\n self.v2i = {v:i for i,v in enumerate(self.i2v)}\n self.fen = BinaryIndexedTree(len(self.i2v))\n self.n = 0\n\n def rank(self, x:T) -> int:\n \'\'\'\n x???????????\n\n :param x: ??????\n :return: x????????\n \'\'\'\n return self.fen[:bisect.bisect_left(self.i2v, x)]\n\n def get(self, rank: int) -> T:\n return self.i2v[self.fen.bisect_left(rank)]\n\n def lower_bound(self, x: T, k: int = 1) -> T:\n \'\'\'\n x???k????????????O(log N)\n\n :param x: ??????\n :param k: ?????????????????1?\n :return: x???k????????\n \'\'\'\n t = self.fen[:bisect.bisect(self.i2v, x)]-k\n if t < 0 or t >= self.n:\n raise IndexError\n return self.fen.bisect_left(t)\n\n def upper_bound(self, x: T, k: int = 1) -> T:\n \'\'\'\n x???k????????????O(log N)\n\n :param x: ??????\n :param k: ?????????????????1?\n :return: x???k????????\n \'\'\'\n t = self.fen[:bisect(self.i2v, x)-1]+k\n if t < 0 or t >= self.n:\n raise IndexError\n return self.fen.bisect_left(t)\n\n def add(self, value: T) -> None:\n pass\n\n def discard(self, value: T) -> None:\n pass\n\n def __contains__(self, x: Any) -> bool:\n pass\n\n def __len__(self) -> int:\n pass\n\n def __iter__(self) -> Iterator[T]:\n pass\n\n\n\nclass SlidingWindowAggregator:\n # ????????\n def __init__(self, op, identity):\n self.op = op\n self.identity = identity\n self.data = []\n self.front = [identity]\n self.back = [identity]\n\n def __len__(self):\n return len(self.front) + len(self.back) - 2\n\n def push(self, x):\n self.data.append(x)\n self.back.append(self.op(self.back[-1], x))\n\n def pop(self):\n if len(self.front) == 1:\n self.move()\n self.front.pop()\n\n def move(self):\n self.back = [self.identity]\n for x in reversed(self.data):\n self.front.append(self.op(x, self.front[-1]))\n self.data.clear()\n\n def get(self):\n return self.op(self.front[-1], self.back[-1])\n\n# bit = BinaryIndexedTree(4)\n# bit[1] += 1\n# bit[2] += 1\n# for i in range(5):\n# print(i, bit.bisect_left(i), bit.bisect_right(i))'), 'lib.graph': (False, 'import itertools\nimport heapq as hq\nfrom lib.misc import min2\nfrom lib.array2d import Array2d\nfrom collections import defaultdict\n\nfrom typing import *\n\nT = TypeVar(\'T\')\n\nINF = 2 ** 62\n\n\nclass BaseWeightedGraph:\n\n def __init__(self, n_vertices: int):\n self.n_vertices = n_vertices\n\n def wadj(self, v: int) -> Iterable[Tuple[int, Any]]:\n """\n Return an iterable of vertices adjacent to v and edge weight\n """\n raise NotImplementedError\n\n def adj(self, v: int) -> Iterable[int]:\n """\n Return an iterable of vertices adjacent to v\n """\n return (u for u, w in self.wadj(v))\n\n @property\n def wedges(self) -> Iterable[Tuple[int, int, Any]]:\n """\n Return an iterable of weighted edges (vertex_1, vertex_2, weight)\n """\n return ((v, u, w) for v in range(self.n_vertices) for u, w in self.wadj(v))\n\n @property\n def edges(self):\n return ((v, u) for v in range(self.n_vertices) for u in self.adj(v))\n\n def dist(self, s: int, t: int, inf=INF):\n return dijkstra(self, s, t, inf)[t]\n\n def warshall_floyd(self, inf=INF):\n dist = Array2d.full(self.n_vertices, self.n_vertices, inf)\n for u, v, w in self.wedges:\n dist[u, v] = w\n for i in range(self.n_vertices):\n dist[i, i] = 0\n for k in range(self.n_vertices):\n for i in range(self.n_vertices):\n for j in range(self.n_vertices):\n dist[i, j] = min2(dist[i, j], dist[i, k] + dist[k, j])\n return dist\n\n def to_wgraph(self) -> \'WeightedGraph\':\n return WeightedGraph.from_directed_edges(self.n_vertices, self.wedges)\n\n def to_reverse_wgraph(self) -> \'WeightedGraph\':\n return WeightedGraph.from_directed_edges(self.n_vertices, ((u, v, w) for v, u, w in self.wedges))\n\n def to_graph(self) -> \'Graph\':\n l = [[] for _ in range(self.n_vertices)]\n for u, v in self.edges:\n l[u].append(v)\n return Graph.from_lil_adj(self.n_vertices, l)\n\n def to_reverse_graph(self) -> \'Graph\':\n l = [[] for _ in range(self.n_vertices)]\n for u, v in self.edges:\n l[v].append(u)\n return Graph.from_lil_adj(self.n_vertices, l)\n\n\nclass WeightedGraph(BaseWeightedGraph):\n\n def __init__(self, n_vertices: int, adj: List[int], weight: List[Any], ind: List[int]):\n super().__init__(n_vertices)\n self._adj = adj\n self._weight = weight\n self._ind = ind\n\n @classmethod\n def from_lil_adj(cls, n_vertices: int, adj_list: Iterable[Sequence[Tuple[int, Any]]],\n n_edges: int) -> \'WeightedGraph\':\n adj = [0] * n_edges\n weight = [0] * n_edges\n ind = [0] * (n_vertices + 1)\n i = 0\n for u, l in enumerate(adj_list):\n ind[u] = i\n for v, w in l:\n adj[i] = v\n weight[i] = w\n i += 1\n ind[n_vertices] = i\n return cls(n_vertices, adj, weight, ind)\n\n @classmethod\n def from_directed_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int, int]]) -> \'WeightedGraph\':\n temp = [[] for _ in range(n_vertices)]\n n_edges = 0\n for u, v, w in edges:\n temp[u].append((v, w))\n n_edges += 1\n return cls.from_lil_adj(n_vertices, temp, n_edges)\n\n @classmethod\n def from_undirected_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int, int]]) -> \'WeightedGraph\':\n return cls.from_directed_edges(n_vertices, itertools.chain(edges, ((u, v, w) for v, u, w in edges)))\n\n def wadj(self, v: int) -> Iterable[Tuple[int, Any]]:\n i, j = self._ind[v], self._ind[v + 1]\n return ((self._adj[k], self._weight[k]) for k in range(i, j))\n\n\nclass ModifiableWeightedGraph(BaseWeightedGraph):\n\n def __init__(self, n_vertices: int, edges: MutableMapping[Tuple[int, int], Any]):\n super().__init__(n_vertices)\n self._edges = edges\n temp = [set() for _ in range(n_vertices)]\n for u, v, w in edges:\n temp[u].add((v, w))\n self._adj = temp\n\n @classmethod\n def from_directed_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int, Any]]) -> \'ModifiableWeightedGraph\':\n return cls(n_vertices, edges)\n\n @classmethod\n def from_undirected_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int, Any]]) -> \'ModifiableWeightedGraph\':\n return cls.from_directed_edges(n_vertices, itertools.chain(edges, ((u, v, w) for v, u, w in edges)))\n\n def wadj(self, v: int) -> Iterable[Tuple[int, Any]]:\n return self._adj[v]\n\n def update_edge(self, v: int, u: int, w: Any) -> None:\n try:\n w_old = self._edges[v, u]\n self._edges[v, u] = w\n self._adj[v].discard((u, w_old))\n self._adj[v].add((u, w))\n except KeyError:\n self._edges[v, u] = w\n self._adj[v].add((u, w))\n\n def delete_edge(self, v: int, u: int) -> None:\n try:\n w = self._edges[v, u]\n del self._edges[v, u]\n self._adj[v].discard((u, w))\n except KeyError:\n pass\n\n\nclass BaseGraph(BaseWeightedGraph):\n\n def adj(self, v):\n raise NotImplementedError\n\n def wadj(self, v):\n return ((u, 1) for u in self.adj(v))\n\n def dist(self, s: int, t: int, inf: Any = INF):\n d = self.bfs(s, t)[t]\n return inf if d == -1 else d\n\n def furthest_vertex(self, v0):\n """\n Returns a vertex that is furthest away from v0, and its distance from v0\n """\n q = [v0]\n visited = [0] * self.n_vertices\n visited[v0] = 1\n x = -1\n rd = 0\n for d in itertools.count():\n if not q:\n rd = d\n break\n x = q[0]\n nq = []\n for v in q:\n for u in self.adj(v):\n if not visited[u]:\n visited[u] = 1\n nq.append(u)\n q = nq\n return x, rd\n\n\nclass Graph(BaseGraph):\n\n def __init__(self, n_vertices: int, adj: List[int], ind: List[int]):\n super().__init__(n_vertices)\n self._adj = adj\n self._ind = ind\n\n @classmethod\n def from_lil_adj(cls, n_vertices: int, adj_list: Iterable[Sequence[int]]) -> \'Graph\':\n n_edges = sum(len(l) for l in adj_list)\n adj = [0] * n_edges\n ind = [0] * (n_vertices + 1)\n i = 0\n for u, l in enumerate(adj_list):\n ind[u] = i\n for v in l:\n adj[i] = v\n i += 1\n ind[n_vertices] = i\n return cls(n_vertices, adj, ind)\n\n @classmethod\n def from_directed_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int]]) -> \'Graph\':\n temp = [[] for _ in range(n_vertices)]\n for u, v in edges:\n temp[u].append(v)\n return cls.from_lil_adj(n_vertices, temp)\n\n @classmethod\n def from_undirected_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int]]) -> \'Graph\':\n temp = [[] for _ in range(n_vertices)]\n for u, v in edges:\n temp[u].append(v)\n temp[v].append(u)\n return cls.from_lil_adj(n_vertices, temp)\n\n def adj(self, v):\n return self._adj[self._ind[v]: self._ind[v + 1]]\n\n\nclass ModifiableGraph(BaseGraph):\n\n def __init__(self, n_vertices: int, adj: List[MutableSet[int]]):\n super().__init__(n_vertices)\n self._adj = adj\n\n @classmethod\n def from_directed_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int]]) -> \'ModifiableGraph\':\n temp = [set() for _ in range(n_vertices)]\n for u, v in edges:\n temp[u].add(v)\n return cls(n_vertices, temp)\n\n @classmethod\n def from_undirected_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int]]) -> \'ModifiableGraph\':\n return cls.from_directed_edges(n_vertices, itertools.chain(edges, ((u, v) for v, u in edges)))\n\n def adj(self, v: int) -> Iterable[int]:\n return self._adj[v]\n\n def add_edge(self, v: int, u: int) -> None:\n self._adj[v].add(u)\n\n def delete_edge(self, v: int, u: int) -> None:\n self._adj[v].discard(u)\n\n\nclass FunctionalGraph(BaseGraph):\n def __init__(self, n_vertices: int, func: List[int]):\n super().__init__(n_vertices)\n self.func = func\n\n def adj(self, v: int) -> Iterable[int]:\n yield self.func[v]\n\n def get_doubling(self, max_length: int) -> Array2d:\n k = max_length.bit_length()\n dbl = Array2d.full(k, self.n_vertices, 0)\n for v in range(self.n_vertices):\n dbl[0, v] = self.func[v]\n for t in range(1, k):\n for v in range(self.n_vertices):\n dbl[t, v] = dbl[t-1, dbl[t-1, v]]\n return dbl\n\n @staticmethod\n def apply_func(v: int, k: int, dbl: Array2d) -> int:\n assert k.bit_length() <= dbl.n\n\n for t in range(dbl.n):\n if k&1:\n v = dbl[t, v]\n k >>= 1\n return v\n\n\nclass Grid(BaseGraph):\n def __init__(self, grid):\n super().__init__(grid.n * grid.m)\n self.grid = grid\n\n def adj(self, v):\n if not self.grid.arr[v]:\n return\n i, j = divmod(v, self.grid.m)\n if i + 1 < self.grid.n and self.grid[i + 1, j]:\n yield v + self.grid.m\n if 0 <= i - 1 and self.grid[i - 1, j]:\n yield v - self.grid.m\n if j + 1 < self.grid.m and self.grid[i, j + 1]:\n yield v + 1\n if 0 <= j - 1 and self.grid[i, j - 1]:\n yield v - 1\n\n\ndef strongly_connected_components(graph: BaseWeightedGraph, rgraph: BaseWeightedGraph = None):\n if rgraph is None:\n rgraph = graph.to_reverse_graph()\n n = graph.n_vertices\n order = []\n color = [0] * n\n for v0 in range(n):\n if color[v0]:\n continue\n color[v0] = -1\n stack = [iter(graph.adj(v0))]\n path = [v0]\n while path:\n for u in stack[-1]:\n if color[u] == 0:\n color[u] = -1\n path.append(u)\n stack.append(iter(graph.adj(u)))\n break\n else:\n v = path.pop()\n order.append(v)\n stack.pop()\n\n label = 0\n for v0 in reversed(order):\n if color[v0] >= 0:\n continue\n color[v0] = label\n stack = [v0]\n while stack:\n v = stack.pop()\n for u in rgraph.adj(v):\n if color[u] < 0:\n color[u] = label\n stack.append(u)\n label += 1\n return label, color\n\n\ndef bfs(graph: BaseWeightedGraph, s: Union[int, Iterable[int]], t: Union[int, Iterable[int]] = -1) -> List[int]:\n """\n ?????????????????\n\n :param graph: ???\n :param s: ????\n :param t: ????\n :return: ?????(s??????????-1)\n """\n dist = [-1] * graph.n_vertices\n\n if isinstance(s, int):\n q = [s]\n dist[s] = 0\n else:\n q = list(s)\n for v in q:\n dist[v] = 0\n\n if isinstance(t, int):\n t = [t]\n else:\n t = list(t)\n if len(t) > 8:\n t = set(t)\n\n for d in range(1, graph.n_vertices):\n nq = []\n for v in q:\n for u in graph.adj(v):\n if dist[u] < 0:\n dist[u] = d\n nq.append(u)\n if u in t:\n return dist\n q = nq\n return dist\n\n\ndef dijkstra(graph: BaseWeightedGraph, s: Union[int, Iterable[int]], t: Union[int, Iterable[int]] = -1,\n inf: int = INF) -> List[int]:\n """\n Returns a list of distance. If starts contains more than one vertex, returns the shortest distance from any of them.\n """\n K = graph.n_vertices.bit_length()\n MASK = (1 << K) - 1\n dist = [inf] * graph.n_vertices\n\n if isinstance(s, int):\n q = [s]\n dist[s] = 0\n else:\n q = list(s)\n for v in q:\n dist[v] = 0\n if isinstance(t, int):\n if t < 0:\n t = []\n else:\n t = [t]\n else:\n t = set(t)\n\n while q:\n x = hq.heappop(q)\n d, v = x >> K, x & MASK\n if v in t:\n return dist\n if d > dist[v]:\n continue\n for u, w in graph.wadj(v):\n if dist[u] > d + w:\n dist[u] = d + w\n hq.heappush(q, ((d + w) << K) | u)\n return dist\n\n\ndef dijkstra_general(graph: BaseWeightedGraph, inf: T, zero: T, s: Union[int, Iterable[int]],\n t: Union[int, Iterable[int]] = -1) -> List[Any]:\n """\n Returns a list of distance. If starts contains more than one vertex, returns the shortest distance from any of them.\n """\n dist = [inf] * graph.n_vertices\n\n if isinstance(s, int):\n q = [(zero, s)]\n dist[s] = zero\n else:\n q = [(zero, v) for v in s]\n for d, v in q:\n dist[v] = zero\n if isinstance(t, int):\n if t < 0:\n t = []\n else:\n t = [t]\n else:\n t = set(t)\n\n while q:\n d, v = hq.heappop(q)\n if v in t:\n return dist\n if d > dist[v]:\n continue\n for u, w in graph.wadj(v):\n nw = d + w\n if dist[u] > nw:\n dist[u] = nw\n hq.heappush(q, (nw, u))\n return dist\n\n\ndef get_dual_graph(n_vertices: int, wedges: Iterable[Tuple[int, int, int]]) -> Tuple[\n List[int], List[int], List[int], List[int]]:\n """\n ?????????????????\n\n (u, v, cap) in E ??????????? (u, v, cap) ? (v, u, 0) ?????????????????????????\n\n :param n_vertices: ???\n :param wedges: ?????\n :return: (???????, ???index?????)\n """\n\n cap = defaultdict(int)\n for u, v, c in wedges:\n cap[(u, v)] += c\n cap[(v, u)] += 0\n temp: List[List[Tuple[int, int]]] = [[] for _ in range(n_vertices)]\n for (u, v), w in cap.items():\n temp[u].append((v, w))\n\n adj = [0] * len(cap)\n weight = [0] * len(cap)\n rev = [0] * len(cap)\n ind = [0] * (n_vertices + 1)\n\n i = 0\n for u, l in enumerate(temp):\n ind[u] = i\n for v, w in l:\n adj[i] = v\n weight[i] = w\n if u < v:\n cap[(v, u)] = i\n else:\n j = cap[(u, v)]\n rev[i] = j\n rev[j] = i\n i += 1\n ind[n_vertices] = i\n\n return adj, weight, ind, rev\n\n\ndef edmonds_karp(n_vertices: int, edges: Iterable[Tuple[int, int, int]], s: int, t: int):\n """\n ????????\n\n ???: ``O(VE^2)``\n\n :param n_vertices: ???\n :param edges: (??1, ??2, ??)?Iterable\n :param s: ??\n :param t: ??\n :return: (????, ?????, ?????)\n """\n\n adj, caps, ind, rev = get_dual_graph(n_vertices, edges)\n\n m0 = max(caps)\n bfs_memo = [0] * n_vertices\n pv = [-1] * n_vertices\n pe = [-1] * n_vertices\n bfs_memo[s] = n_vertices + 1\n offset = 0\n\n def find_path():\n nonlocal offset\n offset += 1\n q = [s]\n while q:\n nq = []\n for v in q:\n if v == t:\n return True\n for i in range(ind[v], ind[v + 1]):\n if caps[i] == 0:\n continue\n u = adj[i]\n if bfs_memo[u] < offset:\n bfs_memo[u] = offset\n pv[u] = v\n pe[u] = i\n nq.append(u)\n q = nq\n return False\n\n res = 0\n flag = find_path()\n while flag:\n v = t\n m = m0\n while pv[v] >= 0:\n e = pe[v]\n m = min2(m, caps[e])\n v = pv[v]\n v = t\n while pv[v] >= 0:\n e = pe[v]\n caps[e] -= m\n caps[rev[e]] += m\n v = pv[v]\n res += m\n flag = find_path()\n return res, WeightedGraph(n_vertices, adj, caps, ind), rev\n\n\ndef min_st_cut(n_vertices: int, edges: Iterable[Tuple[int, int, int]], s: int, t: int):\n """\n ?? ``st`` ?????????\n\n :param n_vertices: ???\n :param edges: ?\n :param s: ??\n :param t: ??\n :return: (?????, ???????(0-1??????), ?????, ?????)\n """\n flow, g, rev = edmonds_karp(n_vertices, edges, s, t)\n stack = [s]\n visited = [0] * n_vertices\n visited[s] = 1\n while stack:\n v = stack.pop()\n for u, w in g.wadj(v):\n if w > 0 and not visited[u]:\n stack.append(u)\n visited[u] = 1\n return flow, visited, g, rev\n\n\nclass MaxFlowGraph:\n class Edge(NamedTuple):\n src: int\n dst: int\n cap: int\n flow: int\n\n class _Edge:\n def __init__(self, dst: int, cap: int) -> None:\n self.dst = dst\n self.cap = cap\n self.rev: Optional[MaxFlowGraph._Edge] = None\n\n def __init__(self, n: int) -> None:\n self._n = n\n self._g: List[List[MaxFlowGraph._Edge]] = [[] for _ in range(n)]\n self._edges: List[MaxFlowGraph._Edge] = []\n\n def add_edge(self, src: int, dst: int, cap: int) -> int:\n assert 0 <= src < self._n\n assert 0 <= dst < self._n\n assert 0 <= cap\n m = len(self._edges)\n e = MaxFlowGraph._Edge(dst, cap)\n re = MaxFlowGraph._Edge(src, 0)\n e.rev = re\n re.rev = e\n self._g[src].append(e)\n self._g[dst].append(re)\n self._edges.append(e)\n return m\n\n def get_edge(self, i: int) -> Edge:\n assert 0 <= i < len(self._edges)\n e = self._edges[i]\n re = cast(MaxFlowGraph._Edge, e.rev)\n return MaxFlowGraph.Edge(\n re.dst,\n e.dst,\n e.cap + re.cap,\n re.cap\n )\n\n def edges(self) -> List[Edge]:\n return [self.get_edge(i) for i in range(len(self._edges))]\n\n def change_edge(self, i: int, new_cap: int, new_flow: int) -> None:\n assert 0 <= i < len(self._edges)\n assert 0 <= new_flow <= new_cap\n e = self._edges[i]\n e.cap = new_cap - new_flow\n assert e.rev is not None\n e.rev.cap = new_flow\n\n def flow(self, s: int, t: int, flow_limit: Optional[int] = None) -> int:\n assert 0 <= s < self._n\n assert 0 <= t < self._n\n assert s != t\n if flow_limit is None:\n flow_limit = cast(int, sum(e.cap for e in self._g[s]))\n\n current_edge = [0] * self._n\n level = [0] * self._n\n\n def fill(arr: List[int], value: int) -> None:\n for i in range(len(arr)):\n arr[i] = value\n\n def bfs() -> bool:\n fill(level, self._n)\n queue = []\n q_front = 0\n queue.append(s)\n level[s] = 0\n while q_front < len(queue):\n v = queue[q_front]\n q_front += 1\n next_level = level[v] + 1\n for e in self._g[v]:\n if e.cap == 0 or level[e.dst] <= next_level:\n continue\n level[e.dst] = next_level\n if e.dst == t:\n return True\n queue.append(e.dst)\n return False\n\n def dfs(lim: int) -> int:\n stack = []\n edge_stack: List[MaxFlowGraph._Edge] = []\n stack.append(t)\n while stack:\n v = stack[-1]\n if v == s:\n flow = min(lim, min(e.cap for e in edge_stack))\n for e in edge_stack:\n e.cap -= flow\n assert e.rev is not None\n e.rev.cap += flow\n return flow\n next_level = level[v] - 1\n while current_edge[v] < len(self._g[v]):\n e = self._g[v][current_edge[v]]\n re = cast(MaxFlowGraph._Edge, e.rev)\n if level[e.dst] != next_level or re.cap == 0:\n current_edge[v] += 1\n continue\n stack.append(e.dst)\n edge_stack.append(re)\n break\n else:\n stack.pop()\n if edge_stack:\n edge_stack.pop()\n level[v] = self._n\n return 0\n\n flow = 0\n while flow < flow_limit:\n if not bfs():\n break\n fill(current_edge, 0)\n while flow < flow_limit:\n f = dfs(flow_limit - flow)\n flow += f\n if f == 0:\n break\n return flow\n\n def min_cut(self, s: int) -> List[bool]:\n visited = [False] * self._n\n stack = [s]\n visited[s] = True\n while stack:\n v = stack.pop()\n for e in self._g[v]:\n if e.cap > 0 and not visited[e.dst]:\n visited[e.dst] = True\n stack.append(e.dst)\n return visited\n\n\nclass MinCostFlowGraph:\n class Edge(NamedTuple):\n src: int\n dst: int\n cap: int\n flow: int\n cost: int\n\n class _Edge:\n def __init__(self, dst: int, cap: int, cost: int) -> None:\n self.dst = dst\n self.cap = cap\n self.cost = cost\n self.rev: Optional[MinCostFlowGraph._Edge] = None\n\n def __init__(self, n: int) -> None:\n self._n = n\n self._g: List[List[MinCostFlowGraph._Edge]] = [[] for _ in range(n)]\n self._edges: List[MinCostFlowGraph._Edge] = []\n\n def add_edge(self, src: int, dst: int, cap: int, cost: int) -> int:\n assert 0 <= src < self._n\n assert 0 <= dst < self._n\n assert 0 <= cap\n m = len(self._edges)\n e = MinCostFlowGraph._Edge(dst, cap, cost)\n re = MinCostFlowGraph._Edge(src, 0, -cost)\n e.rev = re\n re.rev = e\n self._g[src].append(e)\n self._g[dst].append(re)\n self._edges.append(e)\n return m\n\n def get_edge(self, i: int) -> Edge:\n assert 0 <= i < len(self._edges)\n e = self._edges[i]\n re = cast(MinCostFlowGraph._Edge, e.rev)\n return MinCostFlowGraph.Edge(\n re.dst,\n e.dst,\n e.cap + re.cap,\n re.cap,\n e.cost\n )\n\n def edges(self) -> List[Edge]:\n return [self.get_edge(i) for i in range(len(self._edges))]\n\n def flow(self, s: int, t: int,\n flow_limit: Optional[int] = None) -> Tuple[int, int]:\n return self.slope(s, t, flow_limit)[-1]\n\n def slope(self, s: int, t: int,\n flow_limit: Optional[int] = None) -> List[Tuple[int, int]]:\n assert 0 <= s < self._n\n assert 0 <= t < self._n\n assert s != t\n if flow_limit is None:\n flow_limit = cast(int, sum(e.cap for e in self._g[s]))\n\n dual = [0] * self._n\n prev: List[Optional[Tuple[int, MinCostFlowGraph._Edge]]] = [None] * self._n\n\n def refine_dual() -> bool:\n pq = [(0, s)]\n visited = [False] * self._n\n dist: List[Optional[int]] = [None] * self._n\n dist[s] = 0\n while pq:\n dist_v, v = hq.heappop(pq)\n if visited[v]:\n continue\n visited[v] = True\n if v == t:\n break\n dual_v = dual[v]\n for e in self._g[v]:\n w = e.dst\n if visited[w] or e.cap == 0:\n continue\n reduced_cost = e.cost - dual[w] + dual_v\n new_dist = dist_v + reduced_cost\n dist_w = dist[w]\n if dist_w is None or new_dist < dist_w:\n dist[w] = new_dist\n prev[w] = v, e\n hq.heappush(pq, (new_dist, w))\n else:\n return False\n dist_t = dist[t]\n for v in range(self._n):\n if visited[v]:\n dual[v] -= cast(int, dist_t) - cast(int, dist[v])\n return True\n\n flow = 0\n cost = 0\n prev_cost_per_flow: Optional[int] = None\n result = [(flow, cost)]\n while flow < flow_limit:\n if not refine_dual():\n break\n f = flow_limit - flow\n v = t\n while prev[v] is not None:\n u, e = cast(Tuple[int, MinCostFlowGraph._Edge], prev[v])\n f = min(f, e.cap)\n v = u\n v = t\n while prev[v] is not None:\n u, e = cast(Tuple[int, MinCostFlowGraph._Edge], prev[v])\n e.cap -= f\n assert e.rev is not None\n e.rev.cap += f\n v = u\n c = -dual[s]\n flow += f\n cost += f * c\n if c == prev_cost_per_flow:\n result.pop()\n result.append((flow, cost))\n prev_cost_per_flow = c\n return result'), 'lib.itertools': (False, "from itertools import chain, repeat, count, islice\nfrom collections import Counter\n\n\ndef repeat_chain(values, counts):\n return chain.from_iterable(map(repeat, values, counts))\n\n\ndef unique_combinations_from_value_counts(values, counts, r):\n n = len(counts)\n indices = list(islice(repeat_chain(count(), counts), r))\n if len(indices) < r:\n return\n while True:\n yield tuple(values[i] for i in indices)\n for i, j in zip(reversed(range(r)), repeat_chain(reversed(range(n)), reversed(counts))):\n if indices[i] != j:\n break\n else:\n return\n j = indices[i] + 1\n for i, j in zip(range(i, r), repeat_chain(count(j), counts[j:])):\n indices[i] = j\n\n\ndef unique_combinations(iterable, r):\n values, counts = zip(*Counter(iterable).items())\n return unique_combinations_from_value_counts(values, counts, r)\n\n\nclass UniqueCombinations:\n def __init__(self, values, counts, r):\n self.values = values\n self.counts = counts\n self.r = r\n\n # dp[i][k] := # of unique combinations of length k or shorter with elements values[i:]\n dp = [[1]*(r+1) for c in range(len(counts)+1)]\n for i in reversed(range(len(counts))):\n cnt = self.counts[i]\n for k in range(1, r+1):\n dp[i][k] = dp[i][k-1] + dp[i+1][k] - (dp[i+1][k-cnt-1] if k >= cnt+1 else 0)\n self.dp = dp\n\n def __getitem__(self, ind):\n res = []\n for i in range(len(self.counts)):\n for k in reversed(range(1, min(self.r-len(res), self.counts[i])+1)):\n t = self.dp[i+1][self.r - len(res) - k]-(self.dp[i+1][self.r - len(res)-k-1] if self.r - len(res) >= k+1 else 0)\n if ind < t:\n res.extend(self.values[i] for _ in range(k))\n break\n else:\n ind -= t\n return tuple(res)\n\n def __len__(self):\n return self.dp[0][self.r] - self.dp[0][self.r-1]\n\n\n\nif __name__ == '__main__':\n uc = UniqueCombinations([1,2,3], [5,3,1], 4)\n for i in range(len(uc)):\n print(uc[i])\n # print(list(unique_combinations([2, 2, 2, 2, 4], 4)))\n # print(list(unique_combinations_from_value_counts('abc', [1, 2, 3], 3)))\n"), 'lib.matrix': (False, "from lib.array2d import Array2d\n\n\ndef get_general_matrix(zero, one):\n class Matrix(Array2d):\n ZERO = zero\n ONE = one\n\n @classmethod\n def zeros(cls, n, m):\n return cls.full(n, m, cls.ZERO)\n\n @classmethod\n def ones(cls, n, m):\n return cls.full(n, m, cls.ONE)\n\n def __add__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot add matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n return Matrix(self.n, self.m, [x + y for x, y in zip(self.arr, other.arr)])\n\n def __iadd__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n for i, v in enumerate(other.arr):\n self.arr[i] += v\n return self\n\n def __sub__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot subtract matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n return Matrix(self.n, self.m, [x - y for x, y in zip(self.arr, other.arr)])\n\n def __isub__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n for i, v in enumerate(other.arr):\n self.arr[i] -= v\n return self\n\n def __mul__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n return Matrix(self.n, self.m, [x * y for x, y in zip(self.arr, other.arr)])\n\n def __imul__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n for i, v in enumerate(other.arr):\n self.arr[i] *= v\n return self\n\n def __truediv__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n return Matrix(self.n, self.m, [x / y for x, y in zip(self.arr, other.arr)])\n\n def __matmul__(self, other):\n if self.m != other.n:\n raise ValueError(f'Cannot dot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n\n res = self.full(self.n, other.m, self.ZERO)\n\n for i in range(self.n):\n for j in range(other.m):\n c = self.ZERO\n for k in range(self.m):\n c += self[i, k] * other[k, j]\n res[i, j] = c\n return res\n\n def __imatmul__(self, other):\n if self.m != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n if self is other or self.m != other.m:\n return self @ other\n\n row = [self.ZERO] * self.m\n for i in range(self.n):\n t = i * self.m\n for j in range(self.m):\n row[j] = self.arr[j + t]\n for j in range(other.m):\n c = self.ZERO\n for k in range(self.m):\n c += row[k] * other[k, j]\n self[i, j] = c\n return self\n\n def __pow__(self, power, modulo=None):\n if self.n != self.m:\n raise ValueError('pow is supported only for square matrix')\n k = self.n\n res = Matrix.full(k, k, self.ZERO)\n for i in range(k):\n res[i, i] = self.ONE\n\n m = self\n while power > 0:\n if power & 1:\n res @= m\n m @= m\n power >>= 1\n return res\n\n return Matrix\n\n\nIMatrix = get_general_matrix(0, 1)\nFMatrix = get_general_matrix(0.0, 1.0)\n\n\ndef accumulate(mat):\n res = mat.zeros(mat.n + 1, mat.m + 1)\n for i in range(mat.n):\n k = mat.ZERO\n for j in range(mat.m):\n k += mat[i, j]\n res[i + 1, j + 1] = k\n for j in range(1, mat.m + 1):\n k = mat.ZERO\n for i in range(1, mat.n + 1):\n k += res[i, j]\n res[i, j] = k\n return res\n\n\ndef accumulate_prod(mat):\n res = mat.ones(mat.n + 1, mat.m + 1)\n for i in range(mat.n):\n k = mat.ONE\n for j in range(mat.m):\n k *= mat[i, j]\n res[i + 1, j + 1] = k\n for j in range(1, mat.m + 1):\n k = mat.ONE\n for i in range(1, mat.n):\n k *= res[i, j]\n res[i, j] = k\n return res\n"), 'lib.mincostflow': (False, 'from typing import NamedTuple, Optional, List, Tuple, cast\nfrom heapq import heappush, heappop\n\nclass MFGraph:\n class Edge(NamedTuple):\n src: int\n dst: int\n cap: int\n flow: int\n\n class _Edge:\n def __init__(self, dst: int, cap: int) -> None:\n self.dst = dst\n self.cap = cap\n self.rev: Optional[MFGraph._Edge] = None\n\n def __init__(self, n: int) -> None:\n self._n = n\n self._g: List[List[MFGraph._Edge]] = [[] for _ in range(n)]\n self._edges: List[MFGraph._Edge] = []\n\n def add_edge(self, src: int, dst: int, cap: int) -> int:\n assert 0 <= src < self._n\n assert 0 <= dst < self._n\n assert 0 <= cap\n m = len(self._edges)\n e = MFGraph._Edge(dst, cap)\n re = MFGraph._Edge(src, 0)\n e.rev = re\n re.rev = e\n self._g[src].append(e)\n self._g[dst].append(re)\n self._edges.append(e)\n return m\n\n def get_edge(self, i: int) -> Edge:\n assert 0 <= i < len(self._edges)\n e = self._edges[i]\n re = cast(MFGraph._Edge, e.rev)\n return MFGraph.Edge(\n re.dst,\n e.dst,\n e.cap + re.cap,\n re.cap\n )\n\n def edges(self) -> List[Edge]:\n return [self.get_edge(i) for i in range(len(self._edges))]\n\n def change_edge(self, i: int, new_cap: int, new_flow: int) -> None:\n assert 0 <= i < len(self._edges)\n assert 0 <= new_flow <= new_cap\n e = self._edges[i]\n e.cap = new_cap - new_flow\n assert e.rev is not None\n e.rev.cap = new_flow\n\n def flow(self, s: int, t: int, flow_limit: Optional[int] = None) -> int:\n assert 0 <= s < self._n\n assert 0 <= t < self._n\n assert s != t\n if flow_limit is None:\n flow_limit = cast(int, sum(e.cap for e in self._g[s]))\n\n current_edge = [0] * self._n\n level = [0] * self._n\n\n def fill(arr: List[int], value: int) -> None:\n for i in range(len(arr)):\n arr[i] = value\n\n def bfs() -> bool:\n fill(level, self._n)\n queue = []\n q_front = 0\n queue.append(s)\n level[s] = 0\n while q_front < len(queue):\n v = queue[q_front]\n q_front += 1\n next_level = level[v] + 1\n for e in self._g[v]:\n if e.cap == 0 or level[e.dst] <= next_level:\n continue\n level[e.dst] = next_level\n if e.dst == t:\n return True\n queue.append(e.dst)\n return False\n\n def dfs(lim: int) -> int:\n stack = []\n edge_stack: List[MFGraph._Edge] = []\n stack.append(t)\n while stack:\n v = stack[-1]\n if v == s:\n flow = min(lim, min(e.cap for e in edge_stack))\n for e in edge_stack:\n e.cap -= flow\n assert e.rev is not None\n e.rev.cap += flow\n return flow\n next_level = level[v] - 1\n while current_edge[v] < len(self._g[v]):\n e = self._g[v][current_edge[v]]\n re = cast(MFGraph._Edge, e.rev)\n if level[e.dst] != next_level or re.cap == 0:\n current_edge[v] += 1\n continue\n stack.append(e.dst)\n edge_stack.append(re)\n break\n else:\n stack.pop()\n if edge_stack:\n edge_stack.pop()\n level[v] = self._n\n return 0\n\n flow = 0\n while flow < flow_limit:\n if not bfs():\n break\n fill(current_edge, 0)\n while flow < flow_limit:\n f = dfs(flow_limit - flow)\n flow += f\n if f == 0:\n break\n return flow\n\n def min_cut(self, s: int) -> List[bool]:\n visited = [False] * self._n\n stack = [s]\n visited[s] = True\n while stack:\n v = stack.pop()\n for e in self._g[v]:\n if e.cap > 0 and not visited[e.dst]:\n visited[e.dst] = True\n stack.append(e.dst)\n return visited\n\nclass MCFGraph:\n class Edge(NamedTuple):\n src: int\n dst: int\n cap: int\n flow: int\n cost: int\n\n class _Edge:\n def __init__(self, dst: int, cap: int, cost: int) -> None:\n self.dst = dst\n self.cap = cap\n self.cost = cost\n self.rev: Optional[MCFGraph._Edge] = None\n\n def __init__(self, n: int) -> None:\n self._n = n\n self._g: List[List[MCFGraph._Edge]] = [[] for _ in range(n)]\n self._edges: List[MCFGraph._Edge] = []\n\n def add_edge(self, src: int, dst: int, cap: int, cost: int) -> int:\n assert 0 <= src < self._n\n assert 0 <= dst < self._n\n assert 0 <= cap\n m = len(self._edges)\n e = MCFGraph._Edge(dst, cap, cost)\n re = MCFGraph._Edge(src, 0, -cost)\n e.rev = re\n re.rev = e\n self._g[src].append(e)\n self._g[dst].append(re)\n self._edges.append(e)\n return m\n\n def get_edge(self, i: int) -> Edge:\n assert 0 <= i < len(self._edges)\n e = self._edges[i]\n re = cast(MCFGraph._Edge, e.rev)\n return MCFGraph.Edge(\n re.dst,\n e.dst,\n e.cap + re.cap,\n re.cap,\n e.cost\n )\n\n def edges(self) -> List[Edge]:\n return [self.get_edge(i) for i in range(len(self._edges))]\n\n def flow(self, s: int, t: int,\n flow_limit: Optional[int] = None) -> Tuple[int, int]:\n return self.slope(s, t, flow_limit)[-1]\n\n def slope(self, s: int, t: int,\n flow_limit: Optional[int] = None) -> List[Tuple[int, int]]:\n assert 0 <= s < self._n\n assert 0 <= t < self._n\n assert s != t\n if flow_limit is None:\n flow_limit = cast(int, sum(e.cap for e in self._g[s]))\n\n dual = [0] * self._n\n prev: List[Optional[Tuple[int, MCFGraph._Edge]]] = [None] * self._n\n\n def refine_dual() -> bool:\n pq = [(0, s)]\n visited = [False] * self._n\n dist: List[Optional[int]] = [None] * self._n\n dist[s] = 0\n while pq:\n dist_v, v = heappop(pq)\n if visited[v]:\n continue\n visited[v] = True\n if v == t:\n break\n dual_v = dual[v]\n for e in self._g[v]:\n w = e.dst\n if visited[w] or e.cap == 0:\n continue\n reduced_cost = e.cost - dual[w] + dual_v\n new_dist = dist_v + reduced_cost\n dist_w = dist[w]\n if dist_w is None or new_dist < dist_w:\n dist[w] = new_dist\n prev[w] = v, e\n heappush(pq, (new_dist, w))\n else:\n return False\n dist_t = dist[t]\n for v in range(self._n):\n if visited[v]:\n dual[v] -= cast(int, dist_t) - cast(int, dist[v])\n return True\n\n flow = 0\n cost = 0\n prev_cost_per_flow: Optional[int] = None\n result = [(flow, cost)]\n while flow < flow_limit:\n if not refine_dual():\n break\n f = flow_limit - flow\n v = t\n while prev[v] is not None:\n u, e = cast(Tuple[int, MCFGraph._Edge], prev[v])\n f = min(f, e.cap)\n v = u\n v = t\n while prev[v] is not None:\n u, e = cast(Tuple[int, MCFGraph._Edge], prev[v])\n e.cap -= f\n assert e.rev is not None\n e.rev.cap += f\n v = u\n c = -dual[s]\n flow += f\n cost += f * c\n if c == prev_cost_per_flow:\n result.pop()\n result.append((flow, cost))\n prev_cost_per_flow = c\n return result'), 'lib.misc': (False, 'from typing import List, Any, Callable, Sequence, Union, Tuple, TypeVar\nfrom numbers import Integral, Real\nimport sys\nfrom functools import reduce\nfrom itertools import accumulate\nfrom lib.data_structure import BinaryIndexedTree, DisjointSet\nimport bisect\nfrom lib.number_theory import modinv\nfrom collections import deque\n\nT = TypeVar(\'T\')\nM = TypeVar(\'M\')\nV = TypeVar(\'V\')\n\n\n\ndef general_bisect(ng: Integral, ok: Integral, judge: Callable[[Integral], bool]) -> Integral:\n """\n ???????????????????O(log L)??????\n\n :param ng: judge(ng)==False????\n :param ok: judge(ok)==True????\n :param judge: ??????????\n :return: judge(x)==True???????????\n """\n while abs(ng - ok) > 1:\n m = (ng + ok) // 2\n if judge(m):\n ok = m\n else:\n ng = m\n return ok\n\n\ndef general_bisect_float(ng: Real, ok: Real, judge: Callable[[Real], bool], tol: Real) -> Real:\n """\n ???????????????????O(log L)??????\n\n :param ng: judge(ng)==False????\n :param ok: judge(ok)==True????\n :param judge: ??????????\n :return: judge(x)==True???????????\n """\n while abs(ng - ok) > tol:\n m = (ng + ok) / 2\n if judge(m):\n ok = m\n else:\n ng = m\n return ok\n\n\ndef fibonacci_search(left: int, right: int, func: Union[Callable[[int], V], Sequence], inf: V = 2 ** 60) -> Tuple[\n V, int]:\n """\n ??????????????????????????????O(log L)??????\n ???(left, right)?????????\n\n :param left: ?????????????\n :param right: ?????????????\n :param func: ??????\n :param inf: func???\n :return: (func????, ????????func???)\n """\n try:\n func = func.__getitem__\n except AttributeError:\n pass\n f1, f2 = 1, 1\n while f1 + f2 < right - left:\n f1, f2 = f1 + f2, f1\n l = left\n m1 = func(l + f2)\n m2 = func(l + f1)\n while f1 > 2:\n f1, f2 = f2, f1 - f2\n if m1 > m2:\n l += f1\n m1 = m2\n m2 = func(l + f1) if l + f1 < right else inf\n else:\n m2 = m1\n m1 = func(l + f2)\n if m1 < m2:\n return m1, l + 1\n else:\n return m2, l + 2\n\n\ndef max2(x: V, y: V) -> V:\n return x if x > y else y\n\n\ndef min2(x: V, y: V) -> V:\n return x if x < y else y\n\n\nread = sys.stdin.buffer.read\nreadline = sys.stdin.buffer.readline\n\n\ndef rerooting(rooted_tree, merge, identity, finalize):\n """\n merge: (T,T) -> T, (T, merge)?????\n identity: ???\n finalize: (T, V, V) -> T\n\n ????????dp?????\n dp[u,v] = finalize(merge(dp[v,k] for k in adj[v] if k != u), u, v)\n ???(u,v)?? u->v\n """\n N = rooted_tree.n_vertices\n parent = rooted_tree.parent\n children = rooted_tree.children\n order = rooted_tree.dfs_order\n\n # from leaf to parent\n dp_down = [None] * N\n for v in reversed(order):\n dp_down[v] = finalize(reduce(merge,\n (dp_down[c] for c in children[v]),\n identity), parent[v], v)\n\n # from parent to leaf\n dp_up = [None] * N\n dp_up[0] = identity\n for v in order:\n if len(children[v]) == 0:\n continue\n temp = (dp_up[v],) + tuple(dp_down[u] for u in children[v]) + (identity,)\n left = accumulate(temp[:-2], merge)\n right = tuple(accumulate(reversed(temp[2:]), merge))\n for u, l, r in zip(children[v], left, reversed(right)):\n dp_up[u] = finalize(merge(l, r), u, v)\n\n res = [None] * N\n for v, l in enumerate(children):\n res[v] = reduce(merge,\n (dp_down[u] for u in children[v]),\n identity)\n res[v] = merge(res[v], dp_up[v])\n return res, dp_up, dp_down\n\n\ndef rerooting_fast(rooted_tree, merge, identity, finalize):\n """\n merge: (T,T) -> T, (T, merge)?????\n identity: ???\n finalize: (T, V, V) -> T\n\n ????????dp?????\n dp[u,v] = finalize(merge(dp[v,k] for k in adj[v] if k != u), u, v)\n ???(u,v)??\n dp[u,v]: v?????u?????????????????\n """\n dp1 = [identity] * rooted_tree.n_vertices\n dp2 = [identity] * rooted_tree.n_vertices\n\n for v in rooted_tree.post_order:\n t = identity\n for u in rooted_tree.children(v):\n dp2[u] = t\n t = merge(t, finalize(dp1[u], v, u))\n t = identity\n for u in reversed(rooted_tree.children(v)):\n dp2[u] = merge(t, dp2[u])\n t = merge(t, finalize(dp1[u], v, u))\n dp1[v] = t\n for v in rooted_tree.pre_order:\n p = rooted_tree.parent(v)\n if p >= 0:\n dp2[v] = finalize(merge(dp2[v], dp2[p]), v, p)\n dp1[v] = merge(dp1[v], dp2[v])\n return dp1\n\n\ndef longest_increasing_sequence(l, inf, strict=True):\n if not l:\n return 0\n dp = [inf] * len(l)\n if strict:\n for i, v in enumerate(l):\n dp[bisect.bisect_left(dp, v)] = v\n else:\n for i, v in enumerate(l):\n dp[bisect.bisect_right(dp, v)] = v\n\n m = next(n for n in reversed(range(len(l))) if dp[n] < inf) + 1\n return m\n\n\n\n\ndef check_bipartiteness(n_vertices, edges):\n ds = DisjointSet.empty(2 * n_vertices)\n\n for a, b in edges:\n ds.union(a, b + n_vertices)\n ds.union(b, a + n_vertices)\n\n next_color = 0\n color = [-1] * (2 * n_vertices)\n for v in range(n_vertices):\n ra = ds.find(v)\n rb = ds.find(v + n_vertices)\n if ra == rb:\n return None\n if color[ra] < 0:\n color[ra] = next_color\n color[rb] = next_color + 1\n next_color += 2\n color[v] = color[ra]\n color[v + n_vertices] = color[rb]\n return color[:n_vertices]\n\n\ndef small_range_duplicate(a: List[int]) -> Tuple[List[int], List[int]]:\n MASK = (1 << 32) - 1\n n = len(a)\n left = [i - 1 for i in range(n + 1)]\n right = [i + 1 for i in range(n + 1)]\n\n sorted_ind = sorted((~v << 32) | i for i, v in enumerate(a))\n t = 0\n vi = sorted_ind[t]\n i = vi & MASK\n v = ~(vi >> 32)\n while t < n:\n j = i\n l = left[i]\n pi = l\n pv = v\n while v == pv and left[i] == pi:\n pi = i\n t += 1\n if t >= n:\n break\n vi = sorted_ind[t]\n i = vi & MASK\n v = ~(vi >> 32)\n r = right[pi]\n right[l] = r\n while j <= pi:\n nj = right[j]\n left[j] = l\n right[j] = r\n j = nj\n left[r] = l\n\n return left, right\n\n\ndef small_range(a: List[int]) -> Tuple[List[int], List[int]]:\n N = len(a)\n MASK = (1 << 32) - 1\n left = [i - 1 for i in range(N + 1)]\n right = [i + 1 for i in range(N + 1)]\n sorted_ind = sorted((~v << 32) | i for i, v in enumerate(a))\n for v in sorted_ind:\n i = v & MASK\n left[right[-i]] = left[-i]\n right[left[-i]] = right[-i]\n\n return left, right\n\n\ndef popcnt32(n: int) -> int:\n n = n - ((n >> 1) & 0x55555555)\n n = (n & 0x33333333) + ((n >> 2) & 0x33333333)\n return ((((n + (n >> 4)) & 0x0f0f0f0f) * 0x01010101) >> 24) & 0xff\n\n\ndef popcnt64(n: int) -> int:\n n = n - ((n >> 1) & 0x5555555555555555)\n n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333)\n n = (n + (n >> 4)) & 0x0f0f0f0f0f0f0f0f\n return ((((n + (n >> 32)) & 0xffffffff) * 0x01010101) >> 24) & 0xff\n\n\ndef popcnt(n: int) -> int:\n if n < 1 << 32:\n return popcnt32(n)\n elif n < 1 << 64:\n return popcnt64(n)\n else:\n return sum(c == \'1\' for c in bin(n))\n\n\ndef reverse_bits32(x: int):\n x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1)\n x = ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2)\n x = ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4)\n x = ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8)\n return ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16)\n\n\ndef count_inversions(l: List[Any]) -> int:\n """\n ?????????in-place????????\n\n :param l: ???\n :return: ???\n """\n bit = BinaryIndexedTree(len(l))\n res = 0\n for i, v in enumerate(l):\n bit[v] += 1\n res += bit[v + 1:]\n return res\n\n\ndef construct_xor_basis(iterable):\n """\n iterable??xor????????\n\n :param iterable: ?????????????\n :return: ?????int????\n """\n basis = []\n for e in iterable:\n for b in basis:\n e = min2(e, e ^ b)\n if e > 0:\n basis.append(e)\n return basis\n\n\ndef check_xor_span(basis, x):\n """\n x?basis???F2???????????????????\n basis????????????????????????\n\n :param basis: ??\n :param x: ?????\n :return: 0???????????????????????????????????\n """\n for b in basis:\n x = min2(x, x ^ b)\n return x\n\n\ndef get_rolling_hash(mods, bases):\n ib = [modinv(b, m) for b, m in zip(bases, mods)]\n k = len(mods)\n\n class RollingHash:\n """\n RollingHash object represents a hash of a sequence.\n O(1) to append/remove element from both front/end.\n\n """\n def __init__(self, hash, pb, l):\n self.hash = hash\n self.pb = pb\n self.l = l\n\n @classmethod\n def empty(cls):\n return cls([0]*k, [1]*k, 0)\n\n def _append_d(self, v):\n v += 1\n for i in range(k):\n self.hash[i] += v * self.pb[i]\n self.hash[i] %= mods[i]\n self.pb[i] = (self.pb[i]*bases[i]) % mods[i]\n self.l += 1\n\n def _appendleft_d(self, v):\n v += 1\n for i in range(k):\n self.hash[i] *= bases[i]\n self.hash[i] += v\n self.hash[i] %= mods[i]\n self.pb[i] = (self.pb[i]*bases[i]) % mods[i]\n self.l += 1\n\n def _pop_d(self, v):\n v += 1\n for i in range(k):\n self.pb[i] = (self.pb[i]*ib[i]) % mods[i]\n self.hash[i] -= v * self.pb[i]\n self.hash[i] %= mods[i]\n self.l -= 1\n\n def _popleft_d(self, v):\n v += 1\n for i in range(k):\n self.pb[i] = (self.pb[i]*ib[i]) % mods[i]\n self.hash[i] -= v\n self.hash[i] *= ib[i]\n self.hash[i] %= mods[i]\n self.l -= 1\n\n def append(self, v):\n h = self.copy()\n h._append_d(v)\n return h\n\n def appendleft(self, v):\n h = self.copy()\n h._appendleft_d(v)\n return h\n\n def pop(self, v):\n h = self.copy()\n h._pop_d(v)\n return h\n\n def popleft(self, v):\n h = self.copy()\n h._popleft_d(v)\n return h\n\n def __hash__(self):\n return hash(tuple(self.hash))\n\n def copy(self):\n return RollingHash(self.hash[:], self.pb[:], self.l)\n __copy__ = copy\n\n return RollingHash\n\n\ndef sliding_max(l, width):\n res = [0]*(len(l)-width+1)\n q = deque(maxlen=width+1)\n\n for i, v in enumerate(l):\n while q and l[q[0]] <= v:\n q.popleft()\n q.appendleft(i)\n while q[-1]+width <= i:\n q.pop()\n res[i-width+1] = l[q[-1]]\n return res\n\n'), 'lib.modint': (False, "from importlib.util import find_spec, module_from_spec\n\nmodints = {}\n\n\ndef get_modint(mod):\n try:\n return modints[mod]\n except KeyError:\n spec = find_spec('lib._modint')\n module = module_from_spec(spec)\n module.__dict__['MOD'] = mod\n spec.loader.exec_module(module)\n modints[mod] = module.ModInt\n return modints[mod]"), 'lib.number_theory': (False, 'from collections import Counter, defaultdict\nfrom math import sqrt, ceil, gcd\nfrom itertools import count\nfrom typing import *\n\n\ndef sign(x):\n return int(x > 0) - int(x < 0)\n\n\ndef egcd(a: int, b: int) -> Tuple[int, int, int]:\n """\n ?????????\n\n :param a: ??\n :param b: ??\n :return: (x, y, gcd(a,b)). x, y?ax+by=gcd(a,b)????\n """\n s, ps, r, pr = 0, 1, b, a\n while r != 0:\n q = pr // r\n pr, r = r, pr - q * r\n ps, s = s, ps - q * s\n t = (pr - ps * a) // b\n if pr > 0:\n return ps, t, pr\n return -ps, -t, -pr\n\n\ndef modinv(x: int, mod: int) -> int:\n """\n Z/(mod Z)???x???\n\n :param x: ??\n :param mod: ??\n :return: x * y % mod = 1????y\n """\n s, ps, r, pr = 0, 1, mod, x\n while r != 0:\n pr, (q, r) = r, divmod(pr, r)\n ps, s = s, ps - q * s\n if pr == 1:\n return ps if ps >= 0 else ps + mod\n raise ValueError("base is not invertible for the given modulus")\n\n\ndef modpow(x, k, mod):\n """\n Z/(mod Z)???x?k?\n\n :param x: ??\n :param k: ??\n :param mod: ??\n :return: x ** k % mod\n """\n if k < 0:\n x = modinv(x, mod)\n k = -k\n r = 1\n while k != 0:\n if k & 1:\n r = (r * x) % mod\n x = (x * x) % mod\n k >>= 1\n return r\n\n\n# ?????\ndef prime_factors(n):\n """\n n??????????\n\n :param n: ???\n :return: n????????????????generator\n """\n i = 2\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n //= i\n yield i\n if n > 1:\n yield n\n\n\ndef int_product(iterable):\n x = 1\n for y in iterable:\n x *= y\n return x\n\n\n# ?????O(sqrt(n))????\ndef divisors(n):\n for i in range(1, ceil(sqrt(n)) + 1):\n j, r = divmod(n, i)\n if not r:\n yield i\n if i != j:\n yield j\n\n\n# ?????\ndef generate_primes():\n d = defaultdict(list)\n\n for q in count(2):\n if q in d:\n for p in d[q]:\n d[p + q].append(p)\n del d[q]\n else:\n yield q\n d[q * q].append(q)\n\n\ndef totient_factors(n):\n def it():\n prev = -1\n for p in prime_factors(n):\n if p == prev:\n yield p\n else:\n prev = p\n for q in prime_factors(p - 1):\n yield q\n return it()\n\n\ndef primitive_root(mod, phi_factors=None):\n if phi_factors is None:\n phi_factors = tuple(totient_factors(mod))\n phi = int_product(phi_factors)\n primes = set(phi_factors)\n for i in range(2, mod):\n for p in primes:\n if modpow(i, (phi // p), mod) == 1:\n break\n else:\n return i\n else:\n raise ValueError(f\'There is no primitive root for modulo {mod}\')\n\n\ndef lcm(nums: Iterable[int]) -> int:\n m = 1\n for n in nums:\n m *= n // gcd(m, n)\n return m\n\n\ndef chinese_remainder_theorem(reminders: List[int], mods: List[int], mods_lcm: int=-1) -> Tuple[int, int]:\n """\n returns x and lcm(reminders) s.t.\n all(x%m == r for r,m in zip(reminders,mods))\n """\n s = 0\n if mods_lcm < 0:\n mods_lcm = lcm(mods)\n for m, r in zip(mods, reminders):\n p = mods_lcm // m\n s += r * p * modinv(p, m)\n s %= mods_lcm\n return s, mods_lcm\n\n\ndef factorials_with_inv(k, mod):\n """\n 0! ... k! ?????mod????????\n """\n fac = [1] * (k + 1)\n inv = [1] * (k + 1)\n t = 1\n for i in range(1, k + 1):\n t = (t * i) % mod\n fac[i] = t\n t = modinv(t, mod)\n for i in reversed(range(1, k + 1)):\n inv[i] = t\n t = (t * i) % mod\n return fac, inv\n\n\ndef extended_lucas_theorem(mod):\n """\n Returns a function (n,m) -> C(n,m)%mod\n """\n factors = tuple((p, q, p ** q) for p, q in Counter(prime_factors(mod)).items())\n facs = [[0] * k for p, q, k in factors]\n invs = [[0] * k for p, q, k in factors]\n for (p, q, k), fac, inv in zip(factors, facs, invs):\n t = 1\n for n in range(k):\n if n % p != 0:\n t *= n\n t %= k\n fac[n] = t\n t = modinv(t, k)\n for n in reversed(range(k)):\n inv[n] = t\n if n % p != 0:\n t *= n\n t %= k\n\n def helper(n, m):\n l = n - m\n if l < 0:\n return 0\n\n def reminders():\n for (p, q, k), fac, inv in zip(factors, facs, invs):\n a, b, c, e0, eq, i, r = n, m, l, 0, -2, 1, 1\n while a > 0:\n r *= fac[a % k] * inv[b % k] * inv[c % k]\n r %= k\n a, b, c = a // p, b // p, c // p\n if i == q:\n eq = e0\n e0 += a - b - c\n i += 1\n if eq >= 0:\n eq += e0\n if e0 >= q:\n r = 0\n else:\n r *= p ** e0\n r %= k\n if not (p == 2 and q >= 3) and (eq % 2 == 1):\n r = -r\n yield r\n\n return chinese_remainder_theorem(reminders(), (m for _, _, m in factors), mod)[0]\n\n return helper\n\n\ndef lucas_theorem(m, n, mod, comb):\n cnt = 1\n while n > 0:\n m, mr = divmod(m, mod)\n n, nr = divmod(n, mod)\n if mr < nr:\n return 0\n cnt *= comb(mr, nr)\n cnt %= mod\n return cnt\n\n\n# C(n,m) is even iff (~n&m)\n\ndef floor_linear_sum(n, m, a, b):\n """\n returns sum((a*i+b)//m for i in range(n))\n """\n if b < 0:\n t = (-b - 1) // m + 1\n b += m * t\n res = -t * n\n else:\n res = 0\n while True:\n if a >= m:\n res += (n - 1) * n * (a // m) // 2\n a %= m\n if b >= m:\n res += n * (b // m)\n b %= m\n\n y_max = (a * n + b) // m\n if y_max == 0:\n return res\n nx_max = b - y_max * m\n res += (n + nx_max // a) * y_max\n n, m, a, b = y_max, a, m, nx_max % a\n\ndef get_sieve(n):\n sieve = [0]*(n+1)\n for i in range(2, len(sieve)):\n if sieve[i] > 0:\n continue\n sieve[i] = i\n for j in range(i*2, len(sieve), i):\n if sieve[j] == 0:\n sieve[j] = i\n return sieve\n\n\ndef divisors_from_sieve(n, sieve):\n res = [1]\n while n > 1:\n k = sieve[n]\n n //= k\n l = len(res)\n t = k\n res.extend(res[i]*t for i in range(l))\n while n > 1 and sieve[n] == k:\n t *= k\n res.extend(res[i]*t for i in range(l))\n n //= k\n return res\n\n\ndef factorize_from_sieve(n, sieve):\n while n > 1:\n yield sieve[n]\n n //= sieve[n]\n\n\ndef discrete_log(x: int, y: int, m: int) -> int:\n """\n x**k == y mod m ?????????k????\n\n :param x: ???????\n :param y: ??????????\n :param m: mod\n :return: ?????\n """\n\n x = int(x)\n y = int(y)\n m = int(m)\n if y >= m or y < 0:\n return -1\n if x == 0:\n if m == 1:\n return 0\n if y == 1:\n return 0\n if y == 0:\n return 1\n return -1\n p = 3\n tmp = x - 1\n cnt = 0\n primes = []\n counts = []\n ps = 0\n while tmp & 1:\n tmp >>= 1\n cnt += 1\n if cnt:\n primes.append(2)\n counts.append(cnt)\n ps += 1\n tmp += 1\n while tmp != 1:\n cnt = 0\n while tmp % p == 0:\n tmp //= p\n cnt += 1\n if cnt:\n primes.append(p)\n counts.append(cnt)\n ps += 1\n p += 2\n if tmp != 1 and p * p > x:\n primes.append(tmp)\n counts.append(1)\n ps += 1\n break\n tail = 0\n mp = m\n for i in range(ps):\n f = 0\n while mp % primes[i] == 0:\n mp //= primes[i]\n f += 1\n if tail < (f + counts[i] - 1) // counts[i]:\n tail = (f + counts[i] - 1) // counts[i]\n z = 1\n for i in range(tail):\n if z == y:\n return i\n z = z * x % m\n if y % gcd(z, m):\n return -1\n p = 3\n u = mp\n tmp = mp - 1\n if tmp & 1:\n u >>= 1\n while tmp & 1:\n tmp >>= 1\n tmp += 1\n while tmp != 1:\n if tmp % p == 0:\n u //= p\n u *= p - 1\n while tmp % p == 0:\n tmp //= p\n p += 2\n if tmp != 1 and p * p > mp:\n u //= tmp\n u *= tmp - 1\n break\n p = 1\n loop = u\n while p * p <= u:\n if u % p == 0:\n if z * modpow(x, p, m) % m == z:\n loop = p\n break\n ip = u // p\n if z * modpow(x, ip, m) % m == z:\n loop = ip\n p += 1\n l, r = 0, loop+1\n sq = (loop+1) >> 1\n while r - l > 1:\n if sq * sq <= loop:\n l = sq\n else:\n r = sq\n sq = (l + r) >> 1\n if sq * sq < loop:\n sq += 1\n b = modpow(modpow(x, loop-1, m), sq, m)\n d = {}\n f = z\n for i in range(sq):\n d[f] = i\n f = f * x % m\n g = y\n for i in range(sq):\n if g in d:\n return i*sq+d[g]+tail\n g = g * b % m\n return -1\n\n'), 'lib.online_sorted_list': (False, 'import sys\nimport traceback\n\nfrom bisect import bisect_left, bisect_right, insort\nfrom itertools import chain, repeat, starmap\nfrom math import log\nfrom operator import add, eq, ne, gt, ge, lt, le, iadd\nfrom textwrap import dedent\n\ntry:\n from collections.abc import Sequence, MutableSequence\nexcept ImportError:\n from collections import Sequence, MutableSequence\n\nfrom functools import wraps\nfrom sys import hexversion\n\nif hexversion < 0x03000000:\n try:\n from thread import get_ident\n except ImportError:\n from dummy_thread import get_ident\nelse:\n from functools import reduce\n\n try:\n from _thread import get_ident\n except ImportError:\n from _dummy_thread import get_ident\n\n\ndef recursive_repr(fillvalue=\'...\'):\n "Decorator to make a repr function return fillvalue for a recursive call."\n\n # pylint: disable=missing-docstring\n # Copied from reprlib in Python 3\n # https://hg.python.org/cpython/file/3.6/Lib/reprlib.py\n\n def decorating_function(user_function):\n repr_running = set()\n\n @wraps(user_function)\n def wrapper(self):\n key = id(self), get_ident()\n if key in repr_running:\n return fillvalue\n repr_running.add(key)\n try:\n result = user_function(self)\n finally:\n repr_running.discard(key)\n return result\n\n return wrapper\n\n return decorating_function\n\n\nclass OnlineSortedList(MutableSequence):\n """Sorted list is a sorted mutable sequence.\n\n Sorted list values are maintained in sorted order.\n\n Sorted list values must be comparable. The total ordering of values must\n not change while they are stored in the sorted list.\n\n Methods for adding values:\n\n * :func:`SortedList.add`\n * :func:`SortedList.update`\n * :func:`SortedList.__add__`\n * :func:`SortedList.__iadd__`\n * :func:`SortedList.__mul__`\n * :func:`SortedList.__imul__`\n\n Methods for removing values:\n\n * :func:`SortedList.clear`\n * :func:`SortedList.discard`\n * :func:`SortedList.remove`\n * :func:`SortedList.pop`\n * :func:`SortedList.__delitem__`\n\n Methods for looking up values:\n\n * :func:`SortedList.bisect_left`\n * :func:`SortedList.bisect_right`\n * :func:`SortedList.count`\n * :func:`SortedList.index`\n * :func:`SortedList.__contains__`\n * :func:`SortedList.__getitem__`\n\n Methods for iterating values:\n\n * :func:`SortedList.irange`\n * :func:`SortedList.islice`\n * :func:`SortedList.__iter__`\n * :func:`SortedList.__reversed__`\n\n Methods for miscellany:\n\n * :func:`SortedList.copy`\n * :func:`SortedList.__len__`\n * :func:`SortedList.__repr__`\n * :func:`SortedList._check`\n * :func:`SortedList._reset`\n\n Sorted lists use lexicographical ordering semantics when compared to other\n sequences.\n\n Some methods of mutable sequences are not supported and will raise\n not-implemented error.\n\n """\n DEFAULT_LOAD_FACTOR = 1000\n\n def __init__(self, iterable=None, key=None):\n """Initialize sorted list instance.\n\n Optional `iterable` argument provides an initial iterable of values to\n initialize the sorted list.\n\n Runtime complexity: `O(n*log(n))`\n\n >>> sl = SortedList()\n >>> sl\n SortedList([])\n >>> sl = SortedList([3, 1, 2, 5, 4])\n >>> sl\n SortedList([1, 2, 3, 4, 5])\n\n :param iterable: initial values (optional)\n\n """\n assert key is None\n self._len = 0\n self._load = self.DEFAULT_LOAD_FACTOR\n self._lists = []\n self._maxes = []\n self._index = []\n self._offset = 0\n\n if iterable is not None:\n self._update(iterable)\n\n def __new__(cls, iterable=None, key=None):\n """Create new sorted list or sorted-key list instance.\n\n Optional `key`-function argument will return an instance of subtype\n :class:`SortedKeyList`.\n\n >>> sl = SortedList()\n >>> isinstance(sl, SortedList)\n True\n >>> sl = SortedList(key=lambda x: -x)\n >>> isinstance(sl, SortedList)\n True\n >>> isinstance(sl, SortedKeyList)\n True\n\n :param iterable: initial values (optional)\n :param key: function used to extract comparison key (optional)\n :return: sorted list or sorted-key list instance\n\n """\n # pylint: disable=unused-argument\n if key is None:\n return object.__new__(cls)\n else:\n if cls is SortedList:\n return object.__new__(SortedKeyList)\n else:\n raise TypeError(\'inherit SortedKeyList for key argument\')\n\n @property\n def key(self): # pylint: disable=useless-return\n """Function used to extract comparison key from values.\n\n Sorted list compares values directly so the key function is none.\n\n """\n return None\n\n def _reset(self, load):\n """Reset sorted list load factor.\n\n The `load` specifies the load-factor of the list. The default load\n factor of 1000 works well for lists from tens to tens-of-millions of\n values. Good practice is to use a value that is the cube root of the\n list size. With billions of elements, the best load factor depends on\n your usage. It\'s best to leave the load factor at the default until you\n start benchmarking.\n\n See :doc:`implementation` and :doc:`performance-scale` for more\n information.\n\n Runtime complexity: `O(n)`\n\n :param int load: load-factor for sorted list sublists\n\n """\n values = reduce(iadd, self._lists, [])\n self._clear()\n self._load = load\n self._update(values)\n\n def clear(self):\n """Remove all values from sorted list.\n\n Runtime complexity: `O(n)`\n\n """\n self._len = 0\n del self._lists[:]\n del self._maxes[:]\n del self._index[:]\n self._offset = 0\n\n _clear = clear\n\n def add(self, value):\n """Add `value` to sorted list.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList()\n >>> sl.add(3)\n >>> sl.add(1)\n >>> sl.add(2)\n >>> sl\n SortedList([1, 2, 3])\n\n :param value: value to add to sorted list\n\n """\n _lists = self._lists\n _maxes = self._maxes\n\n if _maxes:\n pos = bisect_right(_maxes, value)\n\n if pos == len(_maxes):\n pos -= 1\n _lists[pos].append(value)\n _maxes[pos] = value\n else:\n insort(_lists[pos], value)\n\n self._expand(pos)\n else:\n _lists.append([value])\n _maxes.append(value)\n\n self._len += 1\n\n def _expand(self, pos):\n """Split sublists with length greater than double the load-factor.\n\n Updates the index when the sublist length is less than double the load\n level. This requires incrementing the nodes in a traversal from the\n leaf node to the root. For an example traversal see\n ``SortedList._loc``.\n\n """\n _load = self._load\n _lists = self._lists\n _index = self._index\n\n if len(_lists[pos]) > (_load << 1):\n _maxes = self._maxes\n\n _lists_pos = _lists[pos]\n half = _lists_pos[_load:]\n del _lists_pos[_load:]\n _maxes[pos] = _lists_pos[-1]\n\n _lists.insert(pos + 1, half)\n _maxes.insert(pos + 1, half[-1])\n\n del _index[:]\n else:\n if _index:\n child = self._offset + pos\n while child:\n _index[child] += 1\n child = (child - 1) >> 1\n _index[0] += 1\n\n def update(self, iterable):\n """Update sorted list by adding all values from `iterable`.\n\n Runtime complexity: `O(k*log(n))` -- approximate.\n\n >>> sl = SortedList()\n >>> sl.update([3, 1, 2])\n >>> sl\n SortedList([1, 2, 3])\n\n :param iterable: iterable of values to add\n\n """\n _lists = self._lists\n _maxes = self._maxes\n values = sorted(iterable)\n\n if _maxes:\n if len(values) * 4 >= self._len:\n _lists.append(values)\n values = reduce(iadd, _lists, [])\n values.sort()\n self._clear()\n else:\n _add = self.add\n for val in values:\n _add(val)\n return\n\n _load = self._load\n _lists.extend(values[pos:(pos + _load)]\n for pos in range(0, len(values), _load))\n _maxes.extend(sublist[-1] for sublist in _lists)\n self._len = len(values)\n del self._index[:]\n\n _update = update\n\n def __contains__(self, value):\n """Return true if `value` is an element of the sorted list.\n\n ``sl.__contains__(value)`` <==> ``value in sl``\n\n Runtime complexity: `O(log(n))`\n\n >>> sl = SortedList([1, 2, 3, 4, 5])\n >>> 3 in sl\n True\n\n :param value: search for value in sorted list\n :return: true if `value` in sorted list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return False\n\n pos = bisect_left(_maxes, value)\n\n if pos == len(_maxes):\n return False\n\n _lists = self._lists\n idx = bisect_left(_lists[pos], value)\n\n return _lists[pos][idx] == value\n\n def discard(self, value):\n """Remove `value` from sorted list if it is a member.\n\n If `value` is not a member, do nothing.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList([1, 2, 3, 4, 5])\n >>> sl.discard(5)\n >>> sl.discard(0)\n >>> sl == [1, 2, 3, 4]\n True\n\n :param value: `value` to discard from sorted list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return\n\n pos = bisect_left(_maxes, value)\n\n if pos == len(_maxes):\n return\n\n _lists = self._lists\n idx = bisect_left(_lists[pos], value)\n\n if _lists[pos][idx] == value:\n self._delete(pos, idx)\n\n def remove(self, value):\n """Remove `value` from sorted list; `value` must be a member.\n\n If `value` is not a member, raise ValueError.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList([1, 2, 3, 4, 5])\n >>> sl.remove(5)\n >>> sl == [1, 2, 3, 4]\n True\n >>> sl.remove(0)\n Traceback (most recent call last):\n ...\n ValueError: 0 not in list\n\n :param value: `value` to remove from sorted list\n :raises ValueError: if `value` is not in sorted list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n raise ValueError(\'{0!r} not in list\'.format(value))\n\n pos = bisect_left(_maxes, value)\n\n if pos == len(_maxes):\n raise ValueError(\'{0!r} not in list\'.format(value))\n\n _lists = self._lists\n idx = bisect_left(_lists[pos], value)\n\n if _lists[pos][idx] == value:\n self._delete(pos, idx)\n else:\n raise ValueError(\'{0!r} not in list\'.format(value))\n\n def _delete(self, pos, idx):\n """Delete value at the given `(pos, idx)`.\n\n Combines lists that are less than half the load level.\n\n Updates the index when the sublist length is more than half the load\n level. This requires decrementing the nodes in a traversal from the\n leaf node to the root. For an example traversal see\n ``SortedList._loc``.\n\n :param int pos: lists index\n :param int idx: sublist index\n\n """\n _lists = self._lists\n _maxes = self._maxes\n _index = self._index\n\n _lists_pos = _lists[pos]\n\n del _lists_pos[idx]\n self._len -= 1\n\n len_lists_pos = len(_lists_pos)\n\n if len_lists_pos > (self._load >> 1):\n _maxes[pos] = _lists_pos[-1]\n\n if _index:\n child = self._offset + pos\n while child > 0:\n _index[child] -= 1\n child = (child - 1) >> 1\n _index[0] -= 1\n elif len(_lists) > 1:\n if not pos:\n pos += 1\n\n prev = pos - 1\n _lists[prev].extend(_lists[pos])\n _maxes[prev] = _lists[prev][-1]\n\n del _lists[pos]\n del _maxes[pos]\n del _index[:]\n\n self._expand(prev)\n elif len_lists_pos:\n _maxes[pos] = _lists_pos[-1]\n else:\n del _lists[pos]\n del _maxes[pos]\n del _index[:]\n\n def _loc(self, pos, idx):\n """Convert an index pair (lists index, sublist index) into a single\n index number that corresponds to the position of the value in the\n sorted list.\n\n Many queries require the index be built. Details of the index are\n described in ``SortedList._build_index``.\n\n Indexing requires traversing the tree from a leaf node to the root. The\n parent of each node is easily computable at ``(pos - 1) // 2``.\n\n Left-child nodes are always at odd indices and right-child nodes are\n always at even indices.\n\n When traversing up from a right-child node, increment the total by the\n left-child node.\n\n The final index is the sum from traversal and the index in the sublist.\n\n For example, using the index from ``SortedList._build_index``::\n\n _index = 14 5 9 3 2 4 5\n _offset = 3\n\n Tree::\n\n 14\n 5 9\n 3 2 4 5\n\n Converting an index pair (2, 3) into a single index involves iterating\n like so:\n\n 1. Starting at the leaf node: offset + alpha = 3 + 2 = 5. We identify\n the node as a left-child node. At such nodes, we simply traverse to\n the parent.\n\n 2. At node 9, position 2, we recognize the node as a right-child node\n and accumulate the left-child in our total. Total is now 5 and we\n traverse to the parent at position 0.\n\n 3. Iteration ends at the root.\n\n The index is then the sum of the total and sublist index: 5 + 3 = 8.\n\n :param int pos: lists index\n :param int idx: sublist index\n :return: index in sorted list\n\n """\n if not pos:\n return idx\n\n _index = self._index\n\n if not _index:\n self._build_index()\n\n total = 0\n\n # Increment pos to point in the index to len(self._lists[pos]).\n\n pos += self._offset\n\n # Iterate until reaching the root of the index tree at pos = 0.\n\n while pos:\n\n # Right-child nodes are at odd indices. At such indices\n # account the total below the left child node.\n\n if not pos & 1:\n total += _index[pos - 1]\n\n # Advance pos to the parent node.\n\n pos = (pos - 1) >> 1\n\n return total + idx\n\n def _pos(self, idx):\n """Convert an index into an index pair (lists index, sublist index)\n that can be used to access the corresponding lists position.\n\n Many queries require the index be built. Details of the index are\n described in ``SortedList._build_index``.\n\n Indexing requires traversing the tree to a leaf node. Each node has two\n children which are easily computable. Given an index, pos, the\n left-child is at ``pos * 2 + 1`` and the right-child is at ``pos * 2 +\n 2``.\n\n When the index is less than the left-child, traversal moves to the\n left sub-tree. Otherwise, the index is decremented by the left-child\n and traversal moves to the right sub-tree.\n\n At a child node, the indexing pair is computed from the relative\n position of the child node as compared with the offset and the remaining\n index.\n\n For example, using the index from ``SortedList._build_index``::\n\n _index = 14 5 9 3 2 4 5\n _offset = 3\n\n Tree::\n\n 14\n 5 9\n 3 2 4 5\n\n Indexing position 8 involves iterating like so:\n\n 1. Starting at the root, position 0, 8 is compared with the left-child\n node (5) which it is greater than. When greater the index is\n decremented and the position is updated to the right child node.\n\n 2. At node 9 with index 3, we again compare the index to the left-child\n node with value 4. Because the index is the less than the left-child\n node, we simply traverse to the left.\n\n 3. At node 4 with index 3, we recognize that we are at a leaf node and\n stop iterating.\n\n 4. To compute the sublist index, we subtract the offset from the index\n of the leaf node: 5 - 3 = 2. To compute the index in the sublist, we\n simply use the index remaining from iteration. In this case, 3.\n\n The final index pair from our example is (2, 3) which corresponds to\n index 8 in the sorted list.\n\n :param int idx: index in sorted list\n :return: (lists index, sublist index) pair\n\n """\n if idx < 0:\n last_len = len(self._lists[-1])\n\n if (-idx) <= last_len:\n return len(self._lists) - 1, last_len + idx\n\n idx += self._len\n\n if idx < 0:\n raise IndexError(\'list index out of range\')\n elif idx >= self._len:\n raise IndexError(\'list index out of range\')\n\n if idx < len(self._lists[0]):\n return 0, idx\n\n _index = self._index\n\n if not _index:\n self._build_index()\n\n pos = 0\n child = 1\n len_index = len(_index)\n\n while child < len_index:\n index_child = _index[child]\n\n if idx < index_child:\n pos = child\n else:\n idx -= index_child\n pos = child + 1\n\n child = (pos << 1) + 1\n\n return (pos - self._offset, idx)\n\n def _build_index(self):\n """Build a positional index for indexing the sorted list.\n\n Indexes are represented as binary trees in a dense array notation\n similar to a binary heap.\n\n For example, given a lists representation storing integers::\n\n 0: [1, 2, 3]\n 1: [4, 5]\n 2: [6, 7, 8, 9]\n 3: [10, 11, 12, 13, 14]\n\n The first transformation maps the sub-lists by their length. The\n first row of the index is the length of the sub-lists::\n\n 0: [3, 2, 4, 5]\n\n Each row after that is the sum of consecutive pairs of the previous\n row::\n\n 1: [5, 9]\n 2: [14]\n\n Finally, the index is built by concatenating these lists together::\n\n _index = [14, 5, 9, 3, 2, 4, 5]\n\n An offset storing the start of the first row is also stored::\n\n _offset = 3\n\n When built, the index can be used for efficient indexing into the list.\n See the comment and notes on ``SortedList._pos`` for details.\n\n """\n row0 = list(map(len, self._lists))\n\n if len(row0) == 1:\n self._index[:] = row0\n self._offset = 0\n return\n\n head = iter(row0)\n tail = iter(head)\n row1 = list(starmap(add, zip(head, tail)))\n\n if len(row0) & 1:\n row1.append(row0[-1])\n\n if len(row1) == 1:\n self._index[:] = row1 + row0\n self._offset = 1\n return\n\n size = 2 ** (int(log(len(row1) - 1, 2)) + 1)\n row1.extend(repeat(0, size - len(row1)))\n tree = [row0, row1]\n\n while len(tree[-1]) > 1:\n head = iter(tree[-1])\n tail = iter(head)\n row = list(starmap(add, zip(head, tail)))\n tree.append(row)\n\n reduce(iadd, reversed(tree), self._index)\n self._offset = size * 2 - 1\n\n def __delitem__(self, index):\n """Remove value at `index` from sorted list.\n\n ``sl.__delitem__(index)`` <==> ``del sl[index]``\n\n Supports slicing.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList(\'abcde\')\n >>> del sl[2]\n >>> sl\n SortedList([\'a\', \'b\', \'d\', \'e\'])\n >>> del sl[:2]\n >>> sl\n SortedList([\'d\', \'e\'])\n\n :param index: integer or slice for indexing\n :raises IndexError: if index out of range\n\n """\n if isinstance(index, slice):\n start, stop, step = index.indices(self._len)\n\n if step == 1 and start < stop:\n if start == 0 and stop == self._len:\n return self._clear()\n elif self._len <= 8 * (stop - start):\n values = self._getitem(slice(None, start))\n if stop < self._len:\n values += self._getitem(slice(stop, None))\n self._clear()\n return self._update(values)\n\n indices = range(start, stop, step)\n\n # Delete items from greatest index to least so\n # that the indices remain valid throughout iteration.\n\n if step > 0:\n indices = reversed(indices)\n\n _pos, _delete = self._pos, self._delete\n\n for index in indices:\n pos, idx = _pos(index)\n _delete(pos, idx)\n else:\n pos, idx = self._pos(index)\n self._delete(pos, idx)\n\n def __getitem__(self, index):\n """Lookup value at `index` in sorted list.\n\n ``sl.__getitem__(index)`` <==> ``sl[index]``\n\n Supports slicing.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList(\'abcde\')\n >>> sl[1]\n \'b\'\n >>> sl[-1]\n \'e\'\n >>> sl[2:5]\n [\'c\', \'d\', \'e\']\n\n :param index: integer or slice for indexing\n :return: value or list of values\n :raises IndexError: if index out of range\n\n """\n _lists = self._lists\n\n if isinstance(index, slice):\n start, stop, step = index.indices(self._len)\n\n if step == 1 and start < stop:\n # Whole slice optimization: start to stop slices the whole\n # sorted list.\n\n if start == 0 and stop == self._len:\n return reduce(iadd, self._lists, [])\n\n start_pos, start_idx = self._pos(start)\n start_list = _lists[start_pos]\n stop_idx = start_idx + stop - start\n\n # Small slice optimization: start index and stop index are\n # within the start list.\n\n if len(start_list) >= stop_idx:\n return start_list[start_idx:stop_idx]\n\n if stop == self._len:\n stop_pos = len(_lists) - 1\n stop_idx = len(_lists[stop_pos])\n else:\n stop_pos, stop_idx = self._pos(stop)\n\n prefix = _lists[start_pos][start_idx:]\n middle = _lists[(start_pos + 1):stop_pos]\n result = reduce(iadd, middle, prefix)\n result += _lists[stop_pos][:stop_idx]\n\n return result\n\n if step == -1 and start > stop:\n result = self._getitem(slice(stop + 1, start + 1))\n result.reverse()\n return result\n\n # Return a list because a negative step could\n # reverse the order of the items and this could\n # be the desired behavior.\n\n indices = range(start, stop, step)\n return list(self._getitem(index) for index in indices)\n else:\n if self._len:\n if index == 0:\n return _lists[0][0]\n elif index == -1:\n return _lists[-1][-1]\n else:\n raise IndexError(\'list index out of range\')\n\n if 0 <= index < len(_lists[0]):\n return _lists[0][index]\n\n len_last = len(_lists[-1])\n\n if -len_last < index < 0:\n return _lists[-1][len_last + index]\n\n pos, idx = self._pos(index)\n return _lists[pos][idx]\n\n _getitem = __getitem__\n\n def __setitem__(self, index, value):\n """Raise not-implemented error.\n\n ``sl.__setitem__(index, value)`` <==> ``sl[index] = value``\n\n :raises NotImplementedError: use ``del sl[index]`` and\n ``sl.add(value)`` instead\n\n """\n message = \'use ``del sl[index]`` and ``sl.add(value)`` instead\'\n raise NotImplementedError(message)\n\n def __iter__(self):\n """Return an iterator over the sorted list.\n\n ``sl.__iter__()`` <==> ``iter(sl)``\n\n Iterating the sorted list while adding or deleting values may raise a\n :exc:`RuntimeError` or fail to iterate over all values.\n\n """\n return chain.from_iterable(self._lists)\n\n def __reversed__(self):\n """Return a reverse iterator over the sorted list.\n\n ``sl.__reversed__()`` <==> ``reversed(sl)``\n\n Iterating the sorted list while adding or deleting values may raise a\n :exc:`RuntimeError` or fail to iterate over all values.\n\n """\n return chain.from_iterable(map(reversed, reversed(self._lists)))\n\n def reverse(self):\n """Raise not-implemented error.\n\n Sorted list maintains values in ascending sort order. Values may not be\n reversed in-place.\n\n Use ``reversed(sl)`` for an iterator over values in descending sort\n order.\n\n Implemented to override `MutableSequence.reverse` which provides an\n erroneous default implementation.\n\n :raises NotImplementedError: use ``reversed(sl)`` instead\n\n """\n raise NotImplementedError(\'use ``reversed(sl)`` instead\')\n\n def islice(self, start=None, stop=None, reverse=False):\n """Return an iterator that slices sorted list from `start` to `stop`.\n\n The `start` and `stop` index are treated inclusive and exclusive,\n respectively.\n\n Both `start` and `stop` default to `None` which is automatically\n inclusive of the beginning and end of the sorted list.\n\n When `reverse` is `True` the values are yielded from the iterator in\n reverse order; `reverse` defaults to `False`.\n\n >>> sl = SortedList(\'abcdefghij\')\n >>> it = sl.islice(2, 6)\n >>> list(it)\n [\'c\', \'d\', \'e\', \'f\']\n\n :param int start: start index (inclusive)\n :param int stop: stop index (exclusive)\n :param bool reverse: yield values in reverse order\n :return: iterator\n\n """\n _len = self._len\n\n if not _len:\n return iter(())\n\n start, stop, _ = slice(start, stop).indices(self._len)\n\n if start >= stop:\n return iter(())\n\n _pos = self._pos\n\n min_pos, min_idx = _pos(start)\n\n if stop == _len:\n max_pos = len(self._lists) - 1\n max_idx = len(self._lists[-1])\n else:\n max_pos, max_idx = _pos(stop)\n\n return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)\n\n def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):\n """Return an iterator that slices sorted list using two index pairs.\n\n The index pairs are (min_pos, min_idx) and (max_pos, max_idx), the\n first inclusive and the latter exclusive. See `_pos` for details on how\n an index is converted to an index pair.\n\n When `reverse` is `True`, values are yielded from the iterator in\n reverse order.\n\n """\n _lists = self._lists\n\n if min_pos > max_pos:\n return iter(())\n\n if min_pos == max_pos:\n if reverse:\n indices = reversed(range(min_idx, max_idx))\n return map(_lists[min_pos].__getitem__, indices)\n\n indices = range(min_idx, max_idx)\n return map(_lists[min_pos].__getitem__, indices)\n\n next_pos = min_pos + 1\n\n if next_pos == max_pos:\n if reverse:\n min_indices = range(min_idx, len(_lists[min_pos]))\n max_indices = range(max_idx)\n return chain(\n map(_lists[max_pos].__getitem__, reversed(max_indices)),\n map(_lists[min_pos].__getitem__, reversed(min_indices)),\n )\n\n min_indices = range(min_idx, len(_lists[min_pos]))\n max_indices = range(max_idx)\n return chain(\n map(_lists[min_pos].__getitem__, min_indices),\n map(_lists[max_pos].__getitem__, max_indices),\n )\n\n if reverse:\n min_indices = range(min_idx, len(_lists[min_pos]))\n sublist_indices = range(next_pos, max_pos)\n sublists = map(_lists.__getitem__, reversed(sublist_indices))\n max_indices = range(max_idx)\n return chain(\n map(_lists[max_pos].__getitem__, reversed(max_indices)),\n chain.from_iterable(map(reversed, sublists)),\n map(_lists[min_pos].__getitem__, reversed(min_indices)),\n )\n\n min_indices = range(min_idx, len(_lists[min_pos]))\n sublist_indices = range(next_pos, max_pos)\n sublists = map(_lists.__getitem__, sublist_indices)\n max_indices = range(max_idx)\n return chain(\n map(_lists[min_pos].__getitem__, min_indices),\n chain.from_iterable(sublists),\n map(_lists[max_pos].__getitem__, max_indices),\n )\n\n def irange(self, minimum=None, maximum=None, inclusive=(True, True),\n reverse=False):\n """Create an iterator of values between `minimum` and `maximum`.\n\n Both `minimum` and `maximum` default to `None` which is automatically\n inclusive of the beginning and end of the sorted list.\n\n The argument `inclusive` is a pair of booleans that indicates whether\n the minimum and maximum ought to be included in the range,\n respectively. The default is ``(True, True)`` such that the range is\n inclusive of both minimum and maximum.\n\n When `reverse` is `True` the values are yielded from the iterator in\n reverse order; `reverse` defaults to `False`.\n\n >>> sl = SortedList(\'abcdefghij\')\n >>> it = sl.irange(\'c\', \'f\')\n >>> list(it)\n [\'c\', \'d\', \'e\', \'f\']\n\n :param minimum: minimum value to start iterating\n :param maximum: maximum value to stop iterating\n :param inclusive: pair of booleans\n :param bool reverse: yield values in reverse order\n :return: iterator\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return iter(())\n\n _lists = self._lists\n\n # Calculate the minimum (pos, idx) pair. By default this location\n # will be inclusive in our calculation.\n\n if minimum is None:\n min_pos = 0\n min_idx = 0\n else:\n if inclusive[0]:\n min_pos = bisect_left(_maxes, minimum)\n\n if min_pos == len(_maxes):\n return iter(())\n\n min_idx = bisect_left(_lists[min_pos], minimum)\n else:\n min_pos = bisect_right(_maxes, minimum)\n\n if min_pos == len(_maxes):\n return iter(())\n\n min_idx = bisect_right(_lists[min_pos], minimum)\n\n # Calculate the maximum (pos, idx) pair. By default this location\n # will be exclusive in our calculation.\n\n if maximum is None:\n max_pos = len(_maxes) - 1\n max_idx = len(_lists[max_pos])\n else:\n if inclusive[1]:\n max_pos = bisect_right(_maxes, maximum)\n\n if max_pos == len(_maxes):\n max_pos -= 1\n max_idx = len(_lists[max_pos])\n else:\n max_idx = bisect_right(_lists[max_pos], maximum)\n else:\n max_pos = bisect_left(_maxes, maximum)\n\n if max_pos == len(_maxes):\n max_pos -= 1\n max_idx = len(_lists[max_pos])\n else:\n max_idx = bisect_left(_lists[max_pos], maximum)\n\n return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)\n\n def __len__(self):\n """Return the size of the sorted list.\n\n ``sl.__len__()`` <==> ``len(sl)``\n\n :return: size of sorted list\n\n """\n return self._len\n\n def bisect_left(self, value):\n """Return an index to insert `value` in the sorted list.\n\n If the `value` is already present, the insertion point will be before\n (to the left of) any existing values.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList([10, 11, 12, 13, 14])\n >>> sl.bisect_left(12)\n 2\n\n :param value: insertion index of value in sorted list\n :return: index\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n pos = bisect_left(_maxes, value)\n\n if pos == len(_maxes):\n return self._len\n\n idx = bisect_left(self._lists[pos], value)\n return self._loc(pos, idx)\n\n def bisect_right(self, value):\n """Return an index to insert `value` in the sorted list.\n\n Similar to `bisect_left`, but if `value` is already present, the\n insertion point will be after (to the right of) any existing values.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList([10, 11, 12, 13, 14])\n >>> sl.bisect_right(12)\n 3\n\n :param value: insertion index of value in sorted list\n :return: index\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n pos = bisect_right(_maxes, value)\n\n if pos == len(_maxes):\n return self._len\n\n idx = bisect_right(self._lists[pos], value)\n return self._loc(pos, idx)\n\n bisect = bisect_right\n _bisect_right = bisect_right\n\n def upper_bound(self, x, equal=False):\n k = self.bisect_left(x + equal)\n if k:\n return self[k - 1]\n else:\n sys.stderr.write("upper_bound: no element smaller than {0} in this SortedList\\n".format(x))\n\n def lower_bound(self, x, equal=False):\n k = self.bisect_left(x + 1 - equal) + 1\n if k <= len(self):\n return self[k - 1]\n else:\n sys.stderr.write("lower_bound: no element larger than {0} in this SortedList\\n".format(x))\n\n def count(self, value):\n """Return number of occurrences of `value` in the sorted list.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])\n >>> sl.count(3)\n 3\n\n :param value: value to count in sorted list\n :return: count\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n pos_left = bisect_left(_maxes, value)\n\n if pos_left == len(_maxes):\n return 0\n\n _lists = self._lists\n idx_left = bisect_left(_lists[pos_left], value)\n pos_right = bisect_right(_maxes, value)\n\n if pos_right == len(_maxes):\n return self._len - self._loc(pos_left, idx_left)\n\n idx_right = bisect_right(_lists[pos_right], value)\n\n if pos_left == pos_right:\n return idx_right - idx_left\n\n right = self._loc(pos_right, idx_right)\n left = self._loc(pos_left, idx_left)\n return right - left\n\n def copy(self):\n """Return a shallow copy of the sorted list.\n\n Runtime complexity: `O(n)`\n\n :return: new sorted list\n\n """\n return self.__class__(self)\n\n __copy__ = copy\n\n def append(self, value):\n """Raise not-implemented error.\n\n Implemented to override `MutableSequence.append` which provides an\n erroneous default implementation.\n\n :raises NotImplementedError: use ``sl.add(value)`` instead\n\n """\n raise NotImplementedError(\'use ``sl.add(value)`` instead\')\n\n def extend(self, values):\n """Raise not-implemented error.\n\n Implemented to override `MutableSequence.extend` which provides an\n erroneous default implementation.\n\n :raises NotImplementedError: use ``sl.update(values)`` instead\n\n """\n raise NotImplementedError(\'use ``sl.update(values)`` instead\')\n\n def insert(self, index, value):\n """Raise not-implemented error.\n\n :raises NotImplementedError: use ``sl.add(value)`` instead\n\n """\n raise NotImplementedError(\'use ``sl.add(value)`` instead\')\n\n def pop(self, index=-1):\n """Remove and return value at `index` in sorted list.\n\n Raise :exc:`IndexError` if the sorted list is empty or index is out of\n range.\n\n Negative indices are supported.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList(\'abcde\')\n >>> sl.pop()\n \'e\'\n >>> sl.pop(2)\n \'c\'\n >>> sl\n SortedList([\'a\', \'b\', \'d\'])\n\n :param int index: index of value (default -1)\n :return: value\n :raises IndexError: if index is out of range\n\n """\n if not self._len:\n raise IndexError(\'pop index out of range\')\n\n _lists = self._lists\n\n if index == 0:\n val = _lists[0][0]\n self._delete(0, 0)\n return val\n\n if index == -1:\n pos = len(_lists) - 1\n loc = len(_lists[pos]) - 1\n val = _lists[pos][loc]\n self._delete(pos, loc)\n return val\n\n if 0 <= index < len(_lists[0]):\n val = _lists[0][index]\n self._delete(0, index)\n return val\n\n len_last = len(_lists[-1])\n\n if -len_last < index < 0:\n pos = len(_lists) - 1\n loc = len_last + index\n val = _lists[pos][loc]\n self._delete(pos, loc)\n return val\n\n pos, idx = self._pos(index)\n val = _lists[pos][idx]\n self._delete(pos, idx)\n return val\n\n def index(self, value, start=None, stop=None):\n """Return first index of value in sorted list.\n\n Raise ValueError if `value` is not present.\n\n Index must be between `start` and `stop` for the `value` to be\n considered present. The default value, None, for `start` and `stop`\n indicate the beginning and end of the sorted list.\n\n Negative indices are supported.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList(\'abcde\')\n >>> sl.index(\'d\')\n 3\n >>> sl.index(\'z\')\n Traceback (most recent call last):\n ...\n ValueError: \'z\' is not in list\n\n :param value: value in sorted list\n :param int start: start index (default None, start of sorted list)\n :param int stop: stop index (default None, end of sorted list)\n :return: index of value\n :raises ValueError: if value is not present\n\n """\n _len = self._len\n\n if not _len:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n if start is None:\n start = 0\n if start < 0:\n start += _len\n if start < 0:\n start = 0\n\n if stop is None:\n stop = _len\n if stop < 0:\n stop += _len\n if stop > _len:\n stop = _len\n\n if stop <= start:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n _maxes = self._maxes\n pos_left = bisect_left(_maxes, value)\n\n if pos_left == len(_maxes):\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n _lists = self._lists\n idx_left = bisect_left(_lists[pos_left], value)\n\n if _lists[pos_left][idx_left] != value:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n stop -= 1\n left = self._loc(pos_left, idx_left)\n\n if start <= left:\n if left <= stop:\n return left\n else:\n right = self._bisect_right(value) - 1\n\n if start <= right:\n return start\n\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n def __add__(self, other):\n """Return new sorted list containing all values in both sequences.\n\n ``sl.__add__(other)`` <==> ``sl + other``\n\n Values in `other` do not need to be in sorted order.\n\n Runtime complexity: `O(n*log(n))`\n\n >>> sl1 = SortedList(\'bat\')\n >>> sl2 = SortedList(\'cat\')\n >>> sl1 + sl2\n SortedList([\'a\', \'a\', \'b\', \'c\', \'t\', \'t\'])\n\n :param other: other iterable\n :return: new sorted list\n\n """\n values = reduce(iadd, self._lists, [])\n values.extend(other)\n return self.__class__(values)\n\n __radd__ = __add__\n\n def __iadd__(self, other):\n """Update sorted list with values from `other`.\n\n ``sl.__iadd__(other)`` <==> ``sl += other``\n\n Values in `other` do not need to be in sorted order.\n\n Runtime complexity: `O(k*log(n))` -- approximate.\n\n >>> sl = SortedList(\'bat\')\n >>> sl += \'cat\'\n >>> sl\n SortedList([\'a\', \'a\', \'b\', \'c\', \'t\', \'t\'])\n\n :param other: other iterable\n :return: existing sorted list\n\n """\n self._update(other)\n return self\n\n def __mul__(self, num):\n """Return new sorted list with `num` shallow copies of values.\n\n ``sl.__mul__(num)`` <==> ``sl * num``\n\n Runtime complexity: `O(n*log(n))`\n\n >>> sl = SortedList(\'abc\')\n >>> sl * 3\n SortedList([\'a\', \'a\', \'a\', \'b\', \'b\', \'b\', \'c\', \'c\', \'c\'])\n\n :param int num: count of shallow copies\n :return: new sorted list\n\n """\n values = reduce(iadd, self._lists, []) * num\n return self.__class__(values)\n\n __rmul__ = __mul__\n\n def __imul__(self, num):\n """Update the sorted list with `num` shallow copies of values.\n\n ``sl.__imul__(num)`` <==> ``sl *= num``\n\n Runtime complexity: `O(n*log(n))`\n\n >>> sl = SortedList(\'abc\')\n >>> sl *= 3\n >>> sl\n SortedList([\'a\', \'a\', \'a\', \'b\', \'b\', \'b\', \'c\', \'c\', \'c\'])\n\n :param int num: count of shallow copies\n :return: existing sorted list\n\n """\n values = reduce(iadd, self._lists, []) * num\n self._clear()\n self._update(values)\n return self\n\n def __make_cmp(seq_op, symbol, doc):\n "Make comparator method."\n\n def comparer(self, other):\n "Compare method for sorted list and sequence."\n if not isinstance(other, Sequence):\n return NotImplemented\n\n self_len = self._len\n len_other = len(other)\n\n if self_len != len_other:\n if seq_op is eq:\n return False\n if seq_op is ne:\n return True\n\n for alpha, beta in zip(self, other):\n if alpha != beta:\n return seq_op(alpha, beta)\n\n return seq_op(self_len, len_other)\n\n seq_op_name = seq_op.__name__\n comparer.__name__ = \'__{0}__\'.format(seq_op_name)\n doc_str = """Return true if and only if sorted list is {0} `other`.\n\n ``sl.__{1}__(other)`` <==> ``sl {2} other``\n\n Comparisons use lexicographical order as with sequences.\n\n Runtime complexity: `O(n)`\n\n :param other: `other` sequence\n :return: true if sorted list is {0} `other`\n\n """\n comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))\n return comparer\n\n __eq__ = __make_cmp(eq, \'==\', \'equal to\')\n __ne__ = __make_cmp(ne, \'!=\', \'not equal to\')\n __lt__ = __make_cmp(lt, \'<\', \'less than\')\n __gt__ = __make_cmp(gt, \'>\', \'greater than\')\n __le__ = __make_cmp(le, \'<=\', \'less than or equal to\')\n __ge__ = __make_cmp(ge, \'>=\', \'greater than or equal to\')\n __make_cmp = staticmethod(__make_cmp)\n\n def __reduce__(self):\n values = reduce(iadd, self._lists, [])\n return (type(self), (values,))\n\n @recursive_repr()\n def __repr__(self):\n """Return string representation of sorted list.\n\n ``sl.__repr__()`` <==> ``repr(sl)``\n\n :return: string representation\n\n """\n return \'{0}({1!r})\'.format(type(self).__name__, list(self))\n\n def _check(self):\n """Check invariants of sorted list.\n\n Runtime complexity: `O(n)`\n\n """\n try:\n assert self._load >= 4\n assert len(self._maxes) == len(self._lists)\n assert self._len == sum(len(sublist) for sublist in self._lists)\n\n # Check all sublists are sorted.\n\n for sublist in self._lists:\n for pos in range(1, len(sublist)):\n assert sublist[pos - 1] <= sublist[pos]\n\n # Check beginning/end of sublists are sorted.\n\n for pos in range(1, len(self._lists)):\n assert self._lists[pos - 1][-1] <= self._lists[pos][0]\n\n # Check _maxes index is the last value of each sublist.\n\n for pos in range(len(self._maxes)):\n assert self._maxes[pos] == self._lists[pos][-1]\n\n # Check sublist lengths are less than double load-factor.\n\n double = self._load << 1\n assert all(len(sublist) <= double for sublist in self._lists)\n\n # Check sublist lengths are greater than half load-factor for all\n # but the last sublist.\n\n half = self._load >> 1\n for pos in range(0, len(self._lists) - 1):\n assert len(self._lists[pos]) >= half\n\n if self._index:\n assert self._len == self._index[0]\n assert len(self._index) == self._offset + len(self._lists)\n\n # Check index leaf nodes equal length of sublists.\n\n for pos in range(len(self._lists)):\n leaf = self._index[self._offset + pos]\n assert leaf == len(self._lists[pos])\n\n # Check index branch nodes are the sum of their children.\n\n for pos in range(self._offset):\n child = (pos << 1) + 1\n if child >= len(self._index):\n assert self._index[pos] == 0\n elif child + 1 == len(self._index):\n assert self._index[pos] == self._index[child]\n else:\n child_sum = self._index[child] + self._index[child + 1]\n assert child_sum == self._index[pos]\n except:\n traceback.print_exc(file=sys.stdout)\n print(\'len\', self._len)\n print(\'load\', self._load)\n print(\'offset\', self._offset)\n print(\'len_index\', len(self._index))\n print(\'index\', self._index)\n print(\'len_maxes\', len(self._maxes))\n print(\'maxes\', self._maxes)\n print(\'len_lists\', len(self._lists))\n print(\'lists\', self._lists)\n raise\n\n\ndef identity(value):\n """Identity function."""\n return value\n\n\nclass OnlineSortedKeyList(OnlineSortedList):\n """Sorted-key list is a subtype of sorted list.\n\n The sorted-key list maintains values in comparison order based on the\n result of a key function applied to every value.\n\n All the same methods that are available in :class:`SortedList` are also\n available in :class:`SortedKeyList`.\n\n Additional methods provided:\n\n * :attr:`SortedKeyList.key`\n * :func:`SortedKeyList.bisect_key_left`\n * :func:`SortedKeyList.bisect_key_right`\n * :func:`SortedKeyList.irange_key`\n\n Some examples below use:\n\n >>> from operator import neg\n >>> neg\n <built-in function neg>\n >>> neg(1)\n -1\n\n """\n\n def __init__(self, iterable=None, key=identity):\n """Initialize sorted-key list instance.\n\n Optional `iterable` argument provides an initial iterable of values to\n initialize the sorted-key list.\n\n Optional `key` argument defines a callable that, like the `key`\n argument to Python\'s `sorted` function, extracts a comparison key from\n each value. The default is the identity function.\n\n Runtime complexity: `O(n*log(n))`\n\n >>> from operator import neg\n >>> skl = SortedKeyList(key=neg)\n >>> skl\n SortedKeyList([], key=<built-in function neg>)\n >>> skl = SortedKeyList([3, 1, 2], key=neg)\n >>> skl\n SortedKeyList([3, 2, 1], key=<built-in function neg>)\n\n :param iterable: initial values (optional)\n :param key: function used to extract comparison key (optional)\n\n """\n super().__init__()\n self._key = key\n self._len = 0\n self._load = self.DEFAULT_LOAD_FACTOR\n self._lists = []\n self._keys = []\n self._maxes = []\n self._index = []\n self._offset = 0\n\n if iterable is not None:\n self._update(iterable)\n\n def __new__(cls, iterable=None, key=identity):\n return object.__new__(cls)\n\n @property\n def key(self):\n "Function used to extract comparison key from values."\n return self._key\n\n def clear(self):\n """Remove all values from sorted-key list.\n\n Runtime complexity: `O(n)`\n\n """\n self._len = 0\n del self._lists[:]\n del self._keys[:]\n del self._maxes[:]\n del self._index[:]\n\n _clear = clear\n\n def add(self, value):\n """Add `value` to sorted-key list.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList(key=neg)\n >>> skl.add(3)\n >>> skl.add(1)\n >>> skl.add(2)\n >>> skl\n SortedKeyList([3, 2, 1], key=<built-in function neg>)\n\n :param value: value to add to sorted-key list\n\n """\n _lists = self._lists\n _keys = self._keys\n _maxes = self._maxes\n\n key = self._key(value)\n\n if _maxes:\n pos = bisect_right(_maxes, key)\n\n if pos == len(_maxes):\n pos -= 1\n _lists[pos].append(value)\n _keys[pos].append(key)\n _maxes[pos] = key\n else:\n idx = bisect_right(_keys[pos], key)\n _lists[pos].insert(idx, value)\n _keys[pos].insert(idx, key)\n\n self._expand(pos)\n else:\n _lists.append([value])\n _keys.append([key])\n _maxes.append(key)\n\n self._len += 1\n\n def _expand(self, pos):\n """Split sublists with length greater than double the load-factor.\n\n Updates the index when the sublist length is less than double the load\n level. This requires incrementing the nodes in a traversal from the\n leaf node to the root. For an example traversal see\n ``SortedList._loc``.\n\n """\n _lists = self._lists\n _keys = self._keys\n _index = self._index\n\n if len(_keys[pos]) > (self._load << 1):\n _maxes = self._maxes\n _load = self._load\n\n _lists_pos = _lists[pos]\n _keys_pos = _keys[pos]\n half = _lists_pos[_load:]\n half_keys = _keys_pos[_load:]\n del _lists_pos[_load:]\n del _keys_pos[_load:]\n _maxes[pos] = _keys_pos[-1]\n\n _lists.insert(pos + 1, half)\n _keys.insert(pos + 1, half_keys)\n _maxes.insert(pos + 1, half_keys[-1])\n\n del _index[:]\n else:\n if _index:\n child = self._offset + pos\n while child:\n _index[child] += 1\n child = (child - 1) >> 1\n _index[0] += 1\n\n def update(self, iterable):\n """Update sorted-key list by adding all values from `iterable`.\n\n Runtime complexity: `O(k*log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList(key=neg)\n >>> skl.update([3, 1, 2])\n >>> skl\n SortedKeyList([3, 2, 1], key=<built-in function neg>)\n\n :param iterable: iterable of values to add\n\n """\n _lists = self._lists\n _keys = self._keys\n _maxes = self._maxes\n values = sorted(iterable, key=self._key)\n\n if _maxes:\n if len(values) * 4 >= self._len:\n _lists.append(values)\n values = reduce(iadd, _lists, [])\n values.sort(key=self._key)\n self._clear()\n else:\n _add = self.add\n for val in values:\n _add(val)\n return\n\n _load = self._load\n _lists.extend(values[pos:(pos + _load)]\n for pos in range(0, len(values), _load))\n _keys.extend(list(map(self._key, _list)) for _list in _lists)\n _maxes.extend(sublist[-1] for sublist in _keys)\n self._len = len(values)\n del self._index[:]\n\n _update = update\n\n def __contains__(self, value):\n """Return true if `value` is an element of the sorted-key list.\n\n ``skl.__contains__(value)`` <==> ``value in skl``\n\n Runtime complexity: `O(log(n))`\n\n >>> from operator import neg\n >>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg)\n >>> 3 in skl\n True\n\n :param value: search for value in sorted-key list\n :return: true if `value` in sorted-key list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return False\n\n key = self._key(value)\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n return False\n\n _lists = self._lists\n _keys = self._keys\n\n idx = bisect_left(_keys[pos], key)\n\n len_keys = len(_keys)\n len_sublist = len(_keys[pos])\n\n while True:\n if _keys[pos][idx] != key:\n return False\n if _lists[pos][idx] == value:\n return True\n idx += 1\n if idx == len_sublist:\n pos += 1\n if pos == len_keys:\n return False\n len_sublist = len(_keys[pos])\n idx = 0\n\n def discard(self, value):\n """Remove `value` from sorted-key list if it is a member.\n\n If `value` is not a member, do nothing.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)\n >>> skl.discard(1)\n >>> skl.discard(0)\n >>> skl == [5, 4, 3, 2]\n True\n\n :param value: `value` to discard from sorted-key list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return\n\n key = self._key(value)\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n return\n\n _lists = self._lists\n _keys = self._keys\n idx = bisect_left(_keys[pos], key)\n len_keys = len(_keys)\n len_sublist = len(_keys[pos])\n\n while True:\n if _keys[pos][idx] != key:\n return\n if _lists[pos][idx] == value:\n self._delete(pos, idx)\n return\n idx += 1\n if idx == len_sublist:\n pos += 1\n if pos == len_keys:\n return\n len_sublist = len(_keys[pos])\n idx = 0\n\n def remove(self, value):\n """Remove `value` from sorted-key list; `value` must be a member.\n\n If `value` is not a member, raise ValueError.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg)\n >>> skl.remove(5)\n >>> skl == [4, 3, 2, 1]\n True\n >>> skl.remove(0)\n Traceback (most recent call last):\n ...\n ValueError: 0 not in list\n\n :param value: `value` to remove from sorted-key list\n :raises ValueError: if `value` is not in sorted-key list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n raise ValueError(\'{0!r} not in list\'.format(value))\n\n key = self._key(value)\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n raise ValueError(\'{0!r} not in list\'.format(value))\n\n _lists = self._lists\n _keys = self._keys\n idx = bisect_left(_keys[pos], key)\n len_keys = len(_keys)\n len_sublist = len(_keys[pos])\n\n while True:\n if _keys[pos][idx] != key:\n raise ValueError(\'{0!r} not in list\'.format(value))\n if _lists[pos][idx] == value:\n self._delete(pos, idx)\n return\n idx += 1\n if idx == len_sublist:\n pos += 1\n if pos == len_keys:\n raise ValueError(\'{0!r} not in list\'.format(value))\n len_sublist = len(_keys[pos])\n idx = 0\n\n def _delete(self, pos, idx):\n """Delete value at the given `(pos, idx)`.\n\n Combines lists that are less than half the load level.\n\n Updates the index when the sublist length is more than half the load\n level. This requires decrementing the nodes in a traversal from the\n leaf node to the root. For an example traversal see\n ``SortedList._loc``.\n\n :param int pos: lists index\n :param int idx: sublist index\n\n """\n _lists = self._lists\n _keys = self._keys\n _maxes = self._maxes\n _index = self._index\n keys_pos = _keys[pos]\n lists_pos = _lists[pos]\n\n del keys_pos[idx]\n del lists_pos[idx]\n self._len -= 1\n\n len_keys_pos = len(keys_pos)\n\n if len_keys_pos > (self._load >> 1):\n _maxes[pos] = keys_pos[-1]\n\n if _index:\n child = self._offset + pos\n while child > 0:\n _index[child] -= 1\n child = (child - 1) >> 1\n _index[0] -= 1\n elif len(_keys) > 1:\n if not pos:\n pos += 1\n\n prev = pos - 1\n _keys[prev].extend(_keys[pos])\n _lists[prev].extend(_lists[pos])\n _maxes[prev] = _keys[prev][-1]\n\n del _lists[pos]\n del _keys[pos]\n del _maxes[pos]\n del _index[:]\n\n self._expand(prev)\n elif len_keys_pos:\n _maxes[pos] = keys_pos[-1]\n else:\n del _lists[pos]\n del _keys[pos]\n del _maxes[pos]\n del _index[:]\n\n def irange(self, minimum=None, maximum=None, inclusive=(True, True),\n reverse=False):\n """Create an iterator of values between `minimum` and `maximum`.\n\n Both `minimum` and `maximum` default to `None` which is automatically\n inclusive of the beginning and end of the sorted-key list.\n\n The argument `inclusive` is a pair of booleans that indicates whether\n the minimum and maximum ought to be included in the range,\n respectively. The default is ``(True, True)`` such that the range is\n inclusive of both minimum and maximum.\n\n When `reverse` is `True` the values are yielded from the iterator in\n reverse order; `reverse` defaults to `False`.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([11, 12, 13, 14, 15], key=neg)\n >>> it = skl.irange(14.5, 11.5)\n >>> list(it)\n [14, 13, 12]\n\n :param minimum: minimum value to start iterating\n :param maximum: maximum value to stop iterating\n :param inclusive: pair of booleans\n :param bool reverse: yield values in reverse order\n :return: iterator\n\n """\n min_key = self._key(minimum) if minimum is not None else None\n max_key = self._key(maximum) if maximum is not None else None\n return self._irange_key(\n min_key=min_key, max_key=max_key,\n inclusive=inclusive, reverse=reverse,\n )\n\n def irange_key(self, min_key=None, max_key=None, inclusive=(True, True),\n reverse=False):\n """Create an iterator of values between `min_key` and `max_key`.\n\n Both `min_key` and `max_key` default to `None` which is automatically\n inclusive of the beginning and end of the sorted-key list.\n\n The argument `inclusive` is a pair of booleans that indicates whether\n the minimum and maximum ought to be included in the range,\n respectively. The default is ``(True, True)`` such that the range is\n inclusive of both minimum and maximum.\n\n When `reverse` is `True` the values are yielded from the iterator in\n reverse order; `reverse` defaults to `False`.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([11, 12, 13, 14, 15], key=neg)\n >>> it = skl.irange_key(-14, -12)\n >>> list(it)\n [14, 13, 12]\n\n :param min_key: minimum key to start iterating\n :param max_key: maximum key to stop iterating\n :param inclusive: pair of booleans\n :param bool reverse: yield values in reverse order\n :return: iterator\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return iter(())\n\n _keys = self._keys\n\n # Calculate the minimum (pos, idx) pair. By default this location\n # will be inclusive in our calculation.\n\n if min_key is None:\n min_pos = 0\n min_idx = 0\n else:\n if inclusive[0]:\n min_pos = bisect_left(_maxes, min_key)\n\n if min_pos == len(_maxes):\n return iter(())\n\n min_idx = bisect_left(_keys[min_pos], min_key)\n else:\n min_pos = bisect_right(_maxes, min_key)\n\n if min_pos == len(_maxes):\n return iter(())\n\n min_idx = bisect_right(_keys[min_pos], min_key)\n\n # Calculate the maximum (pos, idx) pair. By default this location\n # will be exclusive in our calculation.\n\n if max_key is None:\n max_pos = len(_maxes) - 1\n max_idx = len(_keys[max_pos])\n else:\n if inclusive[1]:\n max_pos = bisect_right(_maxes, max_key)\n\n if max_pos == len(_maxes):\n max_pos -= 1\n max_idx = len(_keys[max_pos])\n else:\n max_idx = bisect_right(_keys[max_pos], max_key)\n else:\n max_pos = bisect_left(_maxes, max_key)\n\n if max_pos == len(_maxes):\n max_pos -= 1\n max_idx = len(_keys[max_pos])\n else:\n max_idx = bisect_left(_keys[max_pos], max_key)\n\n return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)\n\n _irange_key = irange_key\n\n def bisect_left(self, value):\n """Return an index to insert `value` in the sorted-key list.\n\n If the `value` is already present, the insertion point will be before\n (to the left of) any existing values.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)\n >>> skl.bisect_left(1)\n 4\n\n :param value: insertion index of value in sorted-key list\n :return: index\n\n """\n return self._bisect_key_left(self._key(value))\n\n def bisect_right(self, value):\n """Return an index to insert `value` in the sorted-key list.\n\n Similar to `bisect_left`, but if `value` is already present, the\n insertion point will be after (to the right of) any existing values.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedList([5, 4, 3, 2, 1], key=neg)\n >>> skl.bisect_right(1)\n 5\n\n :param value: insertion index of value in sorted-key list\n :return: index\n\n """\n return self._bisect_key_right(self._key(value))\n\n bisect = bisect_right\n\n def bisect_key_left(self, key):\n """Return an index to insert `key` in the sorted-key list.\n\n If the `key` is already present, the insertion point will be before (to\n the left of) any existing keys.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)\n >>> skl.bisect_key_left(-1)\n 4\n\n :param key: insertion index of key in sorted-key list\n :return: index\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n return self._len\n\n idx = bisect_left(self._keys[pos], key)\n\n return self._loc(pos, idx)\n\n _bisect_key_left = bisect_key_left\n\n def bisect_key_right(self, key):\n """Return an index to insert `key` in the sorted-key list.\n\n Similar to `bisect_key_left`, but if `key` is already present, the\n insertion point will be after (to the right of) any existing keys.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedList([5, 4, 3, 2, 1], key=neg)\n >>> skl.bisect_key_right(-1)\n 5\n\n :param key: insertion index of key in sorted-key list\n :return: index\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n pos = bisect_right(_maxes, key)\n\n if pos == len(_maxes):\n return self._len\n\n idx = bisect_right(self._keys[pos], key)\n\n return self._loc(pos, idx)\n\n bisect_key = bisect_key_right\n _bisect_key_right = bisect_key_right\n\n def count(self, value):\n """Return number of occurrences of `value` in the sorted-key list.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([4, 4, 4, 4, 3, 3, 3, 2, 2, 1], key=neg)\n >>> skl.count(2)\n 2\n\n :param value: value to count in sorted-key list\n :return: count\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n key = self._key(value)\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n return 0\n\n _lists = self._lists\n _keys = self._keys\n idx = bisect_left(_keys[pos], key)\n total = 0\n len_keys = len(_keys)\n len_sublist = len(_keys[pos])\n\n while True:\n if _keys[pos][idx] != key:\n return total\n if _lists[pos][idx] == value:\n total += 1\n idx += 1\n if idx == len_sublist:\n pos += 1\n if pos == len_keys:\n return total\n len_sublist = len(_keys[pos])\n idx = 0\n\n def copy(self):\n """Return a shallow copy of the sorted-key list.\n\n Runtime complexity: `O(n)`\n\n :return: new sorted-key list\n\n """\n return self.__class__(self, key=self._key)\n\n __copy__ = copy\n\n def index(self, value, start=None, stop=None):\n """Return first index of value in sorted-key list.\n\n Raise ValueError if `value` is not present.\n\n Index must be between `start` and `stop` for the `value` to be\n considered present. The default value, None, for `start` and `stop`\n indicate the beginning and end of the sorted-key list.\n\n Negative indices are supported.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)\n >>> skl.index(2)\n 3\n >>> skl.index(0)\n Traceback (most recent call last):\n ...\n ValueError: 0 is not in list\n\n :param value: value in sorted-key list\n :param int start: start index (default None, start of sorted-key list)\n :param int stop: stop index (default None, end of sorted-key list)\n :return: index of value\n :raises ValueError: if value is not present\n\n """\n _len = self._len\n\n if not _len:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n if start is None:\n start = 0\n if start < 0:\n start += _len\n if start < 0:\n start = 0\n\n if stop is None:\n stop = _len\n if stop < 0:\n stop += _len\n if stop > _len:\n stop = _len\n\n if stop <= start:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n _maxes = self._maxes\n key = self._key(value)\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n stop -= 1\n _lists = self._lists\n _keys = self._keys\n idx = bisect_left(_keys[pos], key)\n len_keys = len(_keys)\n len_sublist = len(_keys[pos])\n\n while True:\n if _keys[pos][idx] != key:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n if _lists[pos][idx] == value:\n loc = self._loc(pos, idx)\n if start <= loc <= stop:\n return loc\n elif loc > stop:\n break\n idx += 1\n if idx == len_sublist:\n pos += 1\n if pos == len_keys:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n len_sublist = len(_keys[pos])\n idx = 0\n\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n def __add__(self, other):\n """Return new sorted-key list containing all values in both sequences.\n\n ``skl.__add__(other)`` <==> ``skl + other``\n\n Values in `other` do not need to be in sorted-key order.\n\n Runtime complexity: `O(n*log(n))`\n\n >>> from operator import neg\n >>> skl1 = SortedKeyList([5, 4, 3], key=neg)\n >>> skl2 = SortedKeyList([2, 1, 0], key=neg)\n >>> skl1 + skl2\n SortedKeyList([5, 4, 3, 2, 1, 0], key=<built-in function neg>)\n\n :param other: other iterable\n :return: new sorted-key list\n\n """\n values = reduce(iadd, self._lists, [])\n values.extend(other)\n return self.__class__(values, key=self._key)\n\n __radd__ = __add__\n\n def __mul__(self, num):\n """Return new sorted-key list with `num` shallow copies of values.\n\n ``skl.__mul__(num)`` <==> ``skl * num``\n\n Runtime complexity: `O(n*log(n))`\n\n >>> from operator import neg\n >>> skl = SortedKeyList([3, 2, 1], key=neg)\n >>> skl * 2\n SortedKeyList([3, 3, 2, 2, 1, 1], key=<built-in function neg>)\n\n :param int num: count of shallow copies\n :return: new sorted-key list\n\n """\n values = reduce(iadd, self._lists, []) * num\n return self.__class__(values, key=self._key)\n\n def __reduce__(self):\n values = reduce(iadd, self._lists, [])\n return (type(self), (values, self.key))\n\n @recursive_repr()\n def __repr__(self):\n """Return string representation of sorted-key list.\n\n ``skl.__repr__()`` <==> ``repr(skl)``\n\n :return: string representation\n\n """\n type_name = type(self).__name__\n return \'{0}({1!r}, key={2!r})\'.format(type_name, list(self), self._key)\n\n def _check(self):\n """Check invariants of sorted-key list.\n\n Runtime complexity: `O(n)`\n\n """\n try:\n assert self._load >= 4\n assert len(self._maxes) == len(self._lists) == len(self._keys)\n assert self._len == sum(len(sublist) for sublist in self._lists)\n\n # Check all sublists are sorted.\n\n for sublist in self._keys:\n for pos in range(1, len(sublist)):\n assert sublist[pos - 1] <= sublist[pos]\n\n # Check beginning/end of sublists are sorted.\n\n for pos in range(1, len(self._keys)):\n assert self._keys[pos - 1][-1] <= self._keys[pos][0]\n\n # Check _keys matches _key mapped to _lists.\n\n for val_sublist, key_sublist in zip(self._lists, self._keys):\n assert len(val_sublist) == len(key_sublist)\n for val, key in zip(val_sublist, key_sublist):\n assert self._key(val) == key\n\n # Check _maxes index is the last value of each sublist.\n\n for pos in range(len(self._maxes)):\n assert self._maxes[pos] == self._keys[pos][-1]\n\n # Check sublist lengths are less than double load-factor.\n\n double = self._load << 1\n assert all(len(sublist) <= double for sublist in self._lists)\n\n # Check sublist lengths are greater than half load-factor for all\n # but the last sublist.\n\n half = self._load >> 1\n for pos in range(0, len(self._lists) - 1):\n assert len(self._lists[pos]) >= half\n\n if self._index:\n assert self._len == self._index[0]\n assert len(self._index) == self._offset + len(self._lists)\n\n # Check index leaf nodes equal length of sublists.\n\n for pos in range(len(self._lists)):\n leaf = self._index[self._offset + pos]\n assert leaf == len(self._lists[pos])\n\n # Check index branch nodes are the sum of their children.\n\n for pos in range(self._offset):\n child = (pos << 1) + 1\n if child >= len(self._index):\n assert self._index[pos] == 0\n elif child + 1 == len(self._index):\n assert self._index[pos] == self._index[child]\n else:\n child_sum = self._index[child] + self._index[child + 1]\n assert child_sum == self._index[pos]\n except:\n traceback.print_exc(file=sys.stdout)\n print(\'len\', self._len)\n print(\'load\', self._load)\n print(\'offset\', self._offset)\n print(\'len_index\', len(self._index))\n print(\'index\', self._index)\n print(\'len_maxes\', len(self._maxes))\n print(\'maxes\', self._maxes)\n print(\'len_keys\', len(self._keys))\n print(\'keys\', self._keys)\n print(\'len_lists\', len(self._lists))\n print(\'lists\', self._lists)\n raise\n\n\n'), 'lib.string_search': (False, "import functools\nimport typing\n\n\ndef _sa_naive(s: typing.List[int]) -> typing.List[int]:\n sa = list(range(len(s)))\n return sorted(sa, key=lambda i: s[i:])\n\n\ndef _sa_doubling(s: typing.List[int]) -> typing.List[int]:\n n = len(s)\n sa = list(range(n))\n rnk = s.copy()\n tmp = [0] * n\n k = 1\n while k < n:\n def cmp(x: int, y: int) -> int:\n if rnk[x] != rnk[y]:\n return rnk[x] - rnk[y]\n rx = rnk[x + k] if x + k < n else -1\n ry = rnk[y + k] if y + k < n else -1\n return rx - ry\n sa.sort(key=functools.cmp_to_key(cmp))\n tmp[sa[0]] = 0\n for i in range(1, n):\n tmp[sa[i]] = tmp[sa[i - 1]] + (1 if cmp(sa[i - 1], sa[i]) else 0)\n tmp, rnk = rnk, tmp\n k *= 2\n return sa\n\n\ndef _sa_is(s: typing.List[int], upper: int) -> typing.List[int]:\n threshold_naive = 10\n threshold_doubling = 40\n\n n = len(s)\n\n if n == 0:\n return []\n if n == 1:\n return [0]\n if n == 2:\n if s[0] < s[1]:\n return [0, 1]\n else:\n return [1, 0]\n\n if n < threshold_naive:\n return _sa_naive(s)\n if n < threshold_doubling:\n return _sa_doubling(s)\n\n sa = [0] * n\n ls = [False] * n\n for i in range(n - 2, -1, -1):\n if s[i] == s[i + 1]:\n ls[i] = ls[i + 1]\n else:\n ls[i] = s[i] < s[i + 1]\n\n sum_l = [0] * (upper + 1)\n sum_s = [0] * (upper + 1)\n for i in range(n):\n if not ls[i]:\n sum_s[s[i]] += 1\n else:\n sum_l[s[i] + 1] += 1\n for i in range(upper + 1):\n sum_s[i] += sum_l[i]\n if i < upper:\n sum_l[i + 1] += sum_s[i]\n\n def induce(lms: typing.List[int]) -> None:\n nonlocal sa\n sa = [-1] * n\n\n buf = sum_s.copy()\n for d in lms:\n if d == n:\n continue\n sa[buf[s[d]]] = d\n buf[s[d]] += 1\n\n buf = sum_l.copy()\n sa[buf[s[n - 1]]] = n - 1\n buf[s[n - 1]] += 1\n for i in range(n):\n v = sa[i]\n if v >= 1 and not ls[v - 1]:\n sa[buf[s[v - 1]]] = v - 1\n buf[s[v - 1]] += 1\n\n buf = sum_l.copy()\n for i in range(n - 1, -1, -1):\n v = sa[i]\n if v >= 1 and ls[v - 1]:\n buf[s[v - 1] + 1] -= 1\n sa[buf[s[v - 1] + 1]] = v - 1\n\n lms_map = [-1] * (n + 1)\n m = 0\n for i in range(1, n):\n if not ls[i - 1] and ls[i]:\n lms_map[i] = m\n m += 1\n lms = []\n for i in range(1, n):\n if not ls[i - 1] and ls[i]:\n lms.append(i)\n\n induce(lms)\n\n if m:\n sorted_lms = []\n for v in sa:\n if lms_map[v] != -1:\n sorted_lms.append(v)\n rec_s = [0] * m\n rec_upper = 0\n rec_s[lms_map[sorted_lms[0]]] = 0\n for i in range(1, m):\n left = sorted_lms[i - 1]\n right = sorted_lms[i]\n if lms_map[left] + 1 < m:\n end_l = lms[lms_map[left] + 1]\n else:\n end_l = n\n if lms_map[right] + 1 < m:\n end_r = lms[lms_map[right] + 1]\n else:\n end_r = n\n\n same = True\n if end_l - left != end_r - right:\n same = False\n else:\n while left < end_l:\n if s[left] != s[right]:\n break\n left += 1\n right += 1\n if left == n or s[left] != s[right]:\n same = False\n\n if not same:\n rec_upper += 1\n rec_s[lms_map[sorted_lms[i]]] = rec_upper\n\n rec_sa = _sa_is(rec_s, rec_upper)\n\n for i in range(m):\n sorted_lms[i] = lms[rec_sa[i]]\n induce(sorted_lms)\n\n return sa\n\n\ndef suffix_array(s: typing.Union[str, typing.List[int]],\n upper: typing.Optional[int] = None) -> typing.List[int]:\n '''\n SA-IS, linear-time suffix array construction\n Reference:\n G. Nong, S. Zhang, and W. H. Chan,\n Two Efficient Algorithms for Linear Time Suffix Array Construction\n '''\n\n if isinstance(s, str):\n return _sa_is([ord(c) for c in s], 255)\n elif upper is None:\n n = len(s)\n idx = list(range(n))\n\n def cmp(left: int, right: int) -> int:\n return typing.cast(int, s[left]) - typing.cast(int, s[right])\n\n idx.sort(key=functools.cmp_to_key(cmp))\n s2 = [0] * n\n now = 0\n for i in range(n):\n if i and s[idx[i - 1]] != s[idx[i]]:\n now += 1\n s2[idx[i]] = now\n return _sa_is(s2, now)\n else:\n assert 0 <= upper\n for d in s:\n assert 0 <= d <= upper\n\n return _sa_is(s, upper)\n\n\ndef lcp_array(s: typing.Union[str, typing.List[int]],\n sa: typing.List[int]) -> typing.List[int]:\n '''\n Longest-Common-Prefix computation\n Reference:\n T. Kasai, G. Lee, H. Arimura, S. Arikawa, and K. Park,\n Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its\n Applications\n '''\n\n if isinstance(s, str):\n s = [ord(c) for c in s]\n\n n = len(s)\n assert n >= 1\n\n rnk = [0] * n\n for i in range(n):\n rnk[sa[i]] = i\n\n lcp = [0] * (n - 1)\n h = 0\n for i in range(n):\n if h > 0:\n h -= 1\n if rnk[i] == 0:\n continue\n j = sa[rnk[i] - 1]\n while j + h < n and i + h < n:\n if s[j + h] != s[i + h]:\n break\n h += 1\n lcp[rnk[i] - 1] = h\n\n return lcp\n\n\ndef z_algorithm(s: typing.Union[str, typing.List[int]]) -> typing.List[int]:\n '''\n Z algorithm\n Reference:\n D. Gusfield,\n Algorithms on Strings, Trees, and Sequences: Computer Science and\n Computational Biology\n '''\n\n if isinstance(s, str):\n s = [ord(c) for c in s]\n\n n = len(s)\n if n == 0:\n return []\n\n z = [0] * n\n j = 0\n for i in range(1, n):\n z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j])\n while i + z[i] < n and s[z[i]] == s[i + z[i]]:\n z[i] += 1\n if j + z[j] < i + z[i]:\n j = i\n z[0] = n\n\n return z"), 'lib.transform': (False, 'from cmath import rect, pi\nfrom lib.misc import reverse_bits32\nfrom lib.number_theory import totient_factors, primitive_root, modinv, modpow\nfrom typing import List, TypeVar, Callable\n\nM = TypeVar(\'M\')\n\n\ndef fft(a: List[float], inverse=False):\n one = complex(1.0)\n n = (len(a) - 1).bit_length()\n m = 2 ** n\n a += [complex(0.0)] * (m - len(a))\n pows = [rect(1.0, (-pi if inverse else pi) / (2 ** (n - 1)))]\n for _ in range(n - 1):\n pows.append(pows[-1] ** 2)\n pows.reverse()\n\n shift = 32 - n\n for i in range(m):\n j = reverse_bits32(i) >> shift\n if i < j:\n a[i], a[j] = a[j], a[i]\n\n for i in range(m):\n b = 1\n for w1 in pows:\n if not i & b:\n break\n i ^= b\n w = one\n while not i & b:\n s = a[i]\n t = a[i | b] * w\n a[i] = s + t\n a[i | b] = s - t\n w *= w1\n i += 1\n i ^= b\n b <<= 1\n if inverse:\n c = 1 / m\n for i in range(m):\n a[i] *= c\n return a\n\n\ndef ntt(a: List[int], mod: int, inverse: bool = False):\n if type(a[0]) is not int:\n for i, v in enumerate(a):\n a[i] = int(v)\n n = (len(a) - 1).bit_length()\n d2 = 0\n r = 1\n phi_factors = tuple(totient_factors(mod))\n for p in phi_factors:\n if p == 2:\n d2 += 1\n else:\n r *= p\n if d2 < n:\n raise ValueError(f\'Given array is too long: modulo {mod} only support array length up to {2 ** d2}\')\n\n pr = primitive_root(mod, phi_factors)\n if inverse:\n pr = modinv(pr, mod)\n pows = [modpow(pr, r * 2 ** (d2 - n), mod)]\n for _ in range(n - 1):\n pows.append(pows[-1] ** 2 % mod)\n pows = tuple(reversed(pows))\n\n m = 2 ** n\n a.extend(0 for _ in range(m - len(a)))\n\n shift = 32 - n\n for i in range(m):\n j = reverse_bits32(i) >> shift\n if i < j:\n a[i], a[j] = a[j], a[i]\n\n for i in range(m):\n b = 1\n for w1 in pows:\n if not i & b:\n break\n i ^= b\n w = 1\n while not i & b:\n j = i | b\n s = a[i]\n t = a[j] * w\n a[i] = (s + t) % mod\n a[j] = (s - t) % mod\n w = (w * w1) % mod\n i += 1\n i ^= b\n b <<= 1\n\n if inverse:\n c = modinv(m, mod)\n for i, v in enumerate(a):\n a[i] = (v * c) % mod\n return a\n\n\ndef zeta(data: List[M], operator: Callable[[M, M], M]) -> List[M]:\n r"""\n ??????data????????\n\n ``M`` ?????\n\n ``ouput[i] = sum(data[j] : i|j == i)``\n\n ???: ``O(N * log N)``\n\n ?:\n\n ``zeta(data, add)``: ???????????\n\n ``zeta(data, sub)``: ?????????????????\n\n ??->??->???: ``output[k] = sum(a[i]*b[j] : i|j == k)``\n """\n n = len(data)\n i = 1\n while i < n:\n for j in range(n):\n if j & i != 0:\n data[j] = operator(data[j], data[j ^ i])\n i <<= 1\n return data\n\n\ndef zeta_divisors(data: List[M], operator: Callable[[M, M], M]) -> List[M]:\n r"""\n ??????data????????\n\n ``M`` ?????\n\n ``ouput[i] = sum(data[j] for j in range(N) if j?i???)``\n\n ???: ``O(N * log log N)``\n\n ?:\n\n ``zeta_divisors(data, add)``: ?????????\n\n ``mobius_divisors(data, sub)``: ???????????????\n\n ??->??->???: ``output[k] = sum(a[i]*b[j] : lcm(i,j) == k)``\n """\n n = len(data)\n sieve = [0] * len(data)\n for p in range(2, n):\n if not sieve[p]:\n for a, b in zip(range(1, n), range(p, n, p)):\n sieve[b] = 1\n data[b] = operator(data[b], data[a])\n return data\n\n\ndef mobius_divisors(data: List[M], operator: Callable[[M, M], M]) -> List[M]:\n r"""\n ??????data????????\n\n ``zeta_divisors`` ????\n """\n n = len(data)\n sieve = [0] * len(data)\n for p in range(2, n):\n if not sieve[p]:\n t = (n - 1) // p\n for a, b in zip(range(t, 0, -1), range(t * p, 0, -p)):\n sieve[b] = 1\n data[b] = operator(data[b], data[a])\n return data\n\n\ndef zeta_multiples(data: List[M], operator: Callable[[M, M], M]) -> List[M]:\n r"""\n ??????data????????\n\n ``M`` ?????\n\n ``ouput[i] = sum(data[j] for j in range(N) if j?i???)``\n\n ???: ``O(N * log log N)``\n\n ?:\n\n ``zeta_multiple(data, add)``: ?????????\n\n ``mobius_multiples(data, sub)``: ???????????????\n\n ??->??->???: ``output[k] = sum(a[i]*b[j] : gcd(i,j) == k)``\n """\n n = len(data)\n sieve = [0] * len(data)\n for p in range(2, n):\n if not sieve[p]:\n t = (n - 1) // p\n for a, b in zip(range(t, 0, -1), range(t * p, 0, -p)):\n sieve[b] = 1\n data[a] = operator(data[a], data[b])\n return data\n\n\ndef mobius_multiples(data: List[M], operator: Callable[[M, M], M]) -> List[M]:\n r"""\n ??????data????????\n\n ``zeta_multiples`` ????\n """\n n = len(data)\n sieve = [0] * len(data)\n for p in range(2, n):\n if not sieve[p]:\n for a, b in zip(range(1, n), range(p, n, p)):\n sieve[b] = 1\n data[a] = operator(data[a], data[b])\n return data\n'), 'lib.tree': (False, 'from lib.graph import BaseGraph, Graph\nfrom typing import *\nimport itertools\nimport random\nfrom lib.array2d import Array2d\n\n\nT = TypeVar(\'T\')\n\n\nclass BaseRootedTree(BaseGraph):\n\n def __init__(self, n_vertices, root_vertex=0):\n super().__init__(n_vertices)\n self.root = root_vertex\n\n def parent(self, v: int) -> int:\n raise NotImplementedError\n\n def children(self, v: int) -> Iterable[int]:\n raise NotImplementedError\n\n def adj(self, v) -> Iterable[int]:\n if self.root == v:\n return self.children(v)\n return itertools.chain(self.children(v), (self.parent(v),))\n\n def post_order(self) -> Iterable[int]:\n """\n bottom vertices first\n """\n return (~v for v in self.prepost_order() if v < 0)\n\n def pre_order(self) -> Iterable[int]:\n """\n top vertices first\n """\n stack = [self.root]\n while stack:\n v = stack.pop()\n yield v\n for u in self.children(v):\n stack.append(u)\n\n def prepost_order(self) -> Iterable[int]:\n """\n if v >= 0: it\'s pre-order entry.\n\n otherwise: it\'s post-order entry.\n """\n stack = [~self.root, self.root]\n while stack:\n v = stack.pop()\n yield v\n if v >= 0:\n for u in self.children(v):\n stack.append(~u)\n stack.append(u)\n\n def prepost_indices(self, order=None) -> Tuple[List[int], List[int]]:\n if order is None:\n order = self.prepost_order()\n pre_ind = [0] * self.n_vertices\n post_ind = [0] * self.n_vertices\n for i, t in enumerate(order):\n if t >= 0:\n pre_ind[t] = i\n else:\n post_ind[~t] = i\n return pre_ind, post_ind\n\n def depth(self) -> List[int]:\n depth = [0] * self.n_vertices\n for v in self.pre_order():\n d = depth[v]\n for c in self.children(v):\n depth[c] = d + 1\n return depth\n\n def sort_edge_values(self, wedges: Iterable[Tuple[int, int, T]], default: Optional[T] = None) -> List[T]:\n memo = [default] * self.n_vertices\n for u, v, d in wedges:\n if self.parent(u) == v:\n memo[u] = d\n else:\n memo[v] = d\n return memo\n\n def height(self, depth_list: Optional[List[int]] = None) -> int:\n if depth_list is None:\n depth_list = self.depth()\n return max(depth_list) + 1\n\n def path_to_ancestor(self, v: int, k: int) -> List[int]:\n """\n ??v??k???????????.\n\n :param v: ??\n :param k: ??????????\n :return: ??\n """\n res = [-1] * (k + 1)\n for i in range(k + 1):\n res[i] = v\n v = self.parent(v)\n if v < 0:\n break\n return res\n\n def path(self, s: int, t: int, depth_list: Optional[List[int]] = None) -> List[int]:\n """\n ??s????t?????????\n\n :param s: ??\n :param t: ??\n :param depth_list: ?????????\u3000(optional)\n :return: ??\n """\n if s == t:\n return [s]\n if depth_list:\n d1 = depth_list[s]\n d2 = depth_list[t]\n else:\n d1 = 0\n v = s\n while v >= 0:\n v = self.parent(v)\n d1 += 1\n d2 = 0\n v = t\n while v >= 0:\n v = self.parent(v)\n d2 += 1\n p1 = [s]\n p2 = [t]\n if d1 > d2:\n for _ in range(d1 - d2):\n p1.append(self.parent(p1[-1]))\n else:\n for _ in range(d2 - d1):\n p2.append(self.parent(p2[-1]))\n while p1[-1] != p2[-1]:\n p1.append(self.parent(p1[-1]))\n p2.append(self.parent(p2[-1]))\n p2.pop()\n p1.extend(reversed(p2))\n return p1\n\n def aggregate_root_path(self, aggregate: Callable[[T, int], T], identity: T,\n pre_order: Optional[Iterable[int]] = None) -> List[T]:\n """\n ????????????dp??????.\n\n :param aggregate: (T, V) -> T\n :param identity: ???\n :param pre_order: pre_order????\n :return ?????????????dp?\n """\n if pre_order is None:\n pre_order = self.pre_order()\n\n dp = [identity] * self.n_vertices\n for v in pre_order:\n p = self.parent(v)\n if p >= 0:\n dp[v] = aggregate(dp[p], v)\n return dp\n\n def aggregate_subtree(self, merge: Callable[[int, Callable[[None], Iterator[T]]], T],\n post_order: Optional[Iterable[int]] = None) -> List[T]:\n """\n ???????????????dp??????.\n\n :param merge: (vertex, Iterable(T)) -> T, (T, merge)?????\n :param post_order: post_order????\n :return ???????????????????dp?\n """\n if post_order is None:\n post_order = self.post_order()\n\n dp = [None] * self.n_vertices\n for v in post_order:\n dp[v] = merge(v, lambda: (dp[u] for u in self.children(v)))\n return dp\n\n def solve_rerooting(self, merge: Callable[[T, T, int], T], identity: T, finalize: Callable[[T, int, int], T],\n pre_order: Optional[Iterable[int]] = None) -> List[T]:\n """\n ????dp????\n\n dp[u,v] = finalize(merge(dp[v,k] for k in adj[v] if k != u, v), u, v)\n\n (v?????u?????????????????)\n\n :param merge: (T, T, V) -> T, (T, merge)?????\n :param identity: ???\n :param finalize: (T, V, V) -> T\n :param pre_order: pre_order????\n :return ???????????????dp?\n """\n\n if pre_order is None:\n pre_order = list(self.pre_order())\n dp1 = [identity] * self.n_vertices\n dp2 = [identity] * self.n_vertices\n\n for v in reversed(pre_order):\n t = identity\n for u in self.children(v):\n dp2[u] = t\n t = merge(t, finalize(dp1[u], v, u), v)\n t = identity\n for u in reversed(list(self.children(v))):\n dp2[u] = merge(t, dp2[u], v)\n t = merge(t, finalize(dp1[u], v, u), v)\n dp1[v] = t\n for v in pre_order:\n if v == self.root:\n continue\n p = self.parent(v)\n dp2[v] = finalize(merge(dp2[v], dp2[p], v), v, p)\n dp1[v] = merge(dp1[v], dp2[v], v)\n return dp1\n\n def subtree_sizes(self, post_order: Optional[Iterable[int]] = None):\n def merge(v, values):\n return sum(values)+1\n return self.aggregate_subtree(merge, post_order)\n\n def get_doubling_strategy(self):\n return DoublingStrategy(self)\n\n\nclass DoublingStrategy:\n def __init__(self, tree: BaseRootedTree, depth=None, pre_order=None):\n if pre_order is None:\n pre_order = tree.pre_order()\n if depth is None:\n depth = tree.depth()\n self.depth = depth\n self.tree = tree\n d = (max(depth) + 1).bit_length()\n dbl = Array2d.full(tree.n_vertices, d, -1)\n for v in pre_order:\n u = tree.parent(v)\n dbl[v, 0] = u\n for i in range(d - 1):\n u = dbl[u, i]\n if u < 0:\n break\n dbl[v, i + 1] = u\n self.dbl = dbl\n\n def ancestor_of(self, v: int, k: int) -> int:\n if k > self.depth[v]:\n return -1\n i = 0\n while k:\n if k & 1:\n v = self.dbl[v, i]\n k //= 2\n i += 1\n return v\n\n def lca(self, u: int, v: int) -> int:\n lu, lv = self.depth[u], self.depth[v]\n if lu > lv:\n u = self.ancestor_of(u, lu - lv)\n else:\n v = self.ancestor_of(v, lv - lu)\n if u == v:\n return u\n\n i = self.dbl.m - 1\n while True:\n while i >= 0 and self.dbl[u, i] == self.dbl[v, i]:\n i -= 1\n if i < 0:\n return self.dbl[u, 0]\n u, v = self.dbl[u, i], self.dbl[v, i]\n\n def dist(self, u: int, v: int) -> int:\n return self.depth[u] + self.depth[v] - 2 * self.depth[self.lca(u, v)]\n\n\nclass RootedTree(BaseRootedTree):\n\n def __init__(self, parent: List[int], children: Graph, root_vertex: int):\n super().__init__(len(parent), root_vertex)\n self._parent = parent\n self._children = children\n\n @classmethod\n def from_edges(cls, edges, root_vertex=0):\n n = len(edges) + 1\n g = Graph.from_undirected_edges(n, edges)\n parent = [0] * n\n parent[root_vertex] = -1\n stack = [root_vertex]\n while stack:\n v = stack.pop()\n p = parent[v]\n for u in g.adj(v):\n if u != p:\n parent[u] = v\n stack.append(u)\n return cls.from_parent(parent, root_vertex)\n\n @classmethod\n def from_parent(cls, parent, root_vertex=0):\n return cls(parent,\n Graph.from_directed_edges(len(parent), ((p, v) for v, p in enumerate(parent) if p >= 0)),\n root_vertex)\n\n @classmethod\n def random(cls, n_vertices, root_vertex=0):\n parent = [-1] * n_vertices\n vertices = list(range(root_vertex)) + list(range(root_vertex + 1, n_vertices))\n random.shuffle(vertices)\n vertices.append(root_vertex)\n for i, v in zip(reversed(range(n_vertices)), vertices[-2::-1]):\n parent[v] = vertices[random.randrange(i, n_vertices)]\n return cls.from_parent(parent, root_vertex)\n\n def parent(self, v):\n return self._parent[v]\n\n def children(self, v):\n return self._children.adj(v)\n\n\nclass BinaryTrie:\n class Node:\n def __init__(self):\n self.zero = None\n self.one = None\n self.cnt = 0\n\n def __init__(self, bits):\n self.root = self.Node()\n self.bits = bits\n\n def add(self, v):\n n = self.root\n n.cnt += 1\n for d in reversed(range(self.bits)):\n if (v >> d) & 1:\n if not n.one:\n n.one = BinaryTrie.Node()\n n = n.one\n else:\n if not n.zero:\n n.zero = BinaryTrie.Node()\n n = n.zero\n n.cnt += 1\n return n\n\n def remove(self, v):\n n = self.root\n n.cnt -= 1\n for d in reversed(range(self.bits)):\n if (v >> d) & 1:\n n = n.one\n else:\n n = n.zero\n n.cnt -= 1\n return n\n\n def find_argminxor(self, v):\n n = self.root\n r = 0\n for d in reversed(range(self.bits)):\n if (v >> d) & 1:\n if n.one and n.one.cnt > 0:\n n = n.one\n r |= 1 << d\n else:\n n = n.zero\n else:\n if n.zero and n.zero.cnt > 0:\n n = n.zero\n else:\n n = n.one\n r |= 1 << d\n return r\n\n def find_nth(self):\n raise NotImplementedError\n\n def __contains__(self, v):\n n = self.root\n for d in reversed(range(self.bits)):\n if (v >> d) & 1:\n n = n.one\n else:\n n = n.zero\n if not n or n.cnt == 0:\n return False\n return True\n\n\nclass Trie(BaseRootedTree):\n\n def __init__(self, n_alphabets: int):\n super().__init__(1)\n self.n_alphabets = n_alphabets\n self._parent = [-1]\n self.end = [0]\n self._children = [[-1]*n_alphabets]\n\n def add(self, s):\n v = 0\n for c in s:\n u = self._children[v][c]\n if u < 0:\n self._parent.append(v)\n self.end.append(0)\n self._children[v][c] = self.n_vertices\n self._children.append([-1]*self.n_alphabets)\n self.n_vertices += 1\n v = self._children[v][c]\n self.end[v] = 1\n return v\n\n def parent(self, v: int) -> int:\n return self._parent[v]\n\n def children(self, v):\n return (self._children[v][c] for c in range(self.n_alphabets) if self._children[v][c] >= 0)'), 'lib._modint': (False, 'from lib.number_theory import modinv, modpow\n\nintadd = int.__add__\nintsub = int.__sub__\nintmul = int.__mul__\n\n\nclass ModInt(int):\n mod = MOD\n\n @classmethod\n def v(cls, v):\n return ModInt(v % MOD)\n\n def __neg__(self):\n return ModInt(intsub(MOD, self) if self != 0 else 0)\n\n def __add__(self, other):\n x = intadd(self, other)\n return ModInt(x if x < MOD else x - MOD)\n\n def __sub__(self, other):\n x = intsub(self, other)\n return ModInt(x if x >= 0 else x + MOD)\n\n def __rsub__(self, other):\n x = intsub(other, self)\n return ModInt(x if x >= 0 else x + MOD)\n\n def __mul__(self, other):\n return ModInt(intmul(self, other) % MOD)\n\n def __truediv__(self, other):\n return self * ModInt(other).inv\n\n def __rtruediv__(self, other):\n return self.inv * other\n\n __radd__ = __add__\n __rmul__ = __mul__\n __floordiv__ = __truediv__\n __rfloordiv__ = __rtruediv__\n\n def __pow__(self, other, **kwargs):\n return ModInt(modpow(int(self), int(other), MOD))\n\n @property\n def inv(self):\n return ModInt(modinv(int(self), MOD))\n\n @classmethod\n def sum(cls, iterable):\n r = 0\n for v in iterable:\n r += int(v)\n return ModInt(r)\n\n @classmethod\n def product(cls, iterable):\n r = ModInt(1)\n for v in iterable:\n r *= v\n return r\n'), 'lib': (True, ''), } _sys.meta_path.insert(2, InlineImporter) # Entrypoint from collections import defaultdict from lib.data_structure import SegmentTree, BinaryIndexedTree from lib.misc import min2 q = int(input()) queries = [tuple(map(int,input().split())) for _ in range(q)] i2v = sorted(set(tokens[1] for tokens in queries if tokens[0] < 3)) v2i = {v:i for i,v in enumerate(i2v)} bit = BinaryIndexedTree(len(i2v)) memo = defaultdict(int) seg = SegmentTree.all_identity(min2, 2**30, len(i2v)) dup_cnt = 0 for tokens in queries: if tokens[0] == 1: x = tokens[1] if memo[x] == 0: i = v2i[x] s = bit[:i] l = bit.bisect_left(s) if 0<=l: seg[l] = i2v[l]^x r = bit.bisect_right(s) if r < len(i2v): seg[i] = i2v[r]^x bit[i] += 1 else: dup_cnt += 1 memo[x] += 1 elif tokens[0] == 2: x = tokens[1] if memo[x] == 1: i = v2i[x] bit[i] -= 1 seg[i] = 2**30 s = bit[:i] l = bit.bisect_left(s) if s > 0 else -1 r = bit.bisect_right(s) if 0<=l: if r < len(i2v): seg[l] = i2v[l]^i2v[r] else: seg[l] = 2**30 elif memo[x] == 2: dup_cnt -= 1 memo[x] -= 1 else: print(seg[:] if dup_cnt == 0 else 0) # InlineImporter import os as _os import sys as _sys from functools import lru_cache as _lru_cache from importlib.abc import ExecutionLoader, MetaPathFinder from importlib.machinery import ModuleSpec class InlineImporter(ExecutionLoader, MetaPathFinder): version = None inlined_modules = {} namespace_packages = False @classmethod def find_spec(cls, fullname, path=None, target=None): """Find a spec for a given module. Because we only deal with our inlined module, we don't have to care about path or target. The import machinery also takes care of fully resolving all names, so we just have to deal with the fullnames. """ if fullname in cls.inlined_modules: # We have inlined this module, so return the spec ms = ModuleSpec(fullname, cls, origin=cls.get_filename(fullname), is_package=cls.is_package(fullname)) ms.has_location = True if cls.namespace_packages and ms.submodule_search_locations is not None: for p in _sys.path: ms.submodule_search_locations.append(_os.path.join(p, _os.path.dirname(ms.origin))) return ms return None @staticmethod def _call_with_frames_removed(f, *args, **kwds): """remove_importlib_frames in import.c will always remove sequences of importlib frames that end with a call to this function Use it instead of a normal call in places where including the importlib frames introduces unwanted noise into the traceback (e.g. when executing module code) """ return f(*args, **kwds) @classmethod def create_module(cls, spec): """Create a module using the default machinery.""" return None @classmethod def exec_module(cls, module): """Execute the module.""" code = cls.get_code(module.__name__) if code is None: raise ImportError("cannot load module {!r} when get_code() returns None".format(module.__name__)) cls._call_with_frames_removed(exec, code, module.__dict__) @classmethod @_lru_cache(maxsize=None) def get_filename(cls, fullname): """Returns the Raises ImportError if the module cannot be found. """ if fullname not in cls.inlined_modules: raise ImportError mod = cls.inlined_modules[fullname] origin = fullname if mod[0]: origin = ".".join([origin, "__init__"]) origin = ".".join([origin.replace(".", "/"), "py"]) return origin @classmethod @_lru_cache(maxsize=None) def is_package(cls, fullname): if fullname not in cls.inlined_modules: raise ImportError return cls.inlined_modules[fullname][0] @classmethod def get_source(cls, fullname): if fullname not in cls.inlined_modules: raise ImportError return cls.inlined_modules[fullname][1] @classmethod def get_code(cls, fullname): """Method to return the code object for fullname. Should return None if not applicable (e.g. built-in module). Raise ImportError if the module cannot be found. """ source = cls.get_source(fullname) if source is None: return None try: path = cls.get_filename(fullname) except ImportError: return cls.source_to_code(source) else: return cls.source_to_code(source, path) InlineImporter.version = '0.0.4' InlineImporter.inlined_modules = { 'lib.array2d': (False, "class Array2dView:\n def __init__(self, arr, i_indices, j_indices):\n self.arr = arr\n self.i_indices = i_indices\n self.j_indices = j_indices\n self.n = len(i_indices)\n self.m = len(j_indices)\n \n def _get_view(self, i, j):\n i = self.i_indices[i]\n j = self.j_indices[j]\n return Array2dView(self.arr, i, j)\n\n def get_ind(self, i, j):\n return self.i_indices[i]+self.j_indices[j]\n \n def __getitem__(self, index):\n i, j = index\n try:\n return self.arr[self.get_ind(i,j)]\n except TypeError:\n return self._get_view(i, j)\n \n def __setitem__(self, index, value):\n i, j = index\n try:\n self.arr[self.get_ind(i,j)] = value\n except TypeError:\n x = self._get_view(i, j)\n for i in x.i_indices:\n for j in x.j_indices:\n self.arr[i+j] = value\n \n def __iter__(self):\n for i in self.i_indices:\n for j in self.j_indices:\n yield self.arr[i+j]\n \n def __reversed__(self):\n for i in reversed(self.i_indices):\n for j in reversed(self.j_indices):\n yield self.arr[i+j]\n \n def __str__(self):\n m = max(len(str(v)) for v in self)\n res = ['']*len(self.i_indices)\n row = ['']*(len(self.j_indices)+2)\n for ri,i in enumerate(self.i_indices):\n if ri == 0:\n row[0] = '['\n else:\n row[0] = ' '\n if ri == len(self.i_indices)-1:\n row[-1] = ']\\n'\n for rj,j in enumerate(self.j_indices):\n row[rj+1] = f'{str(self.arr[i+j]):>{m+1}}'\n res[ri] = ''.join(row)\n return '\\n'.join(res)\n \n def copy(self):\n return Array2d(len(self.i_indices), len(self.j_indices), list(self))\n\n\nclass Array2d:\n def __init__(self, n, m, arr):\n self.n = n\n self.m = m\n self.arr = arr\n \n @classmethod\n def full(cls, n, m, fill_value):\n return cls(n, m, [fill_value]*(n*m))\n \n @classmethod\n def from_list(cls, lst):\n n,m = len(lst), len(lst[0])\n arr = [lst[0]]*(n*m)\n k = 0\n for row in lst:\n for v in row:\n arr[k] = v\n k += 1\n return cls(n, m, arr)\n \n def _get_view(self, i, j):\n i = tuple(range(0, self.n*self.m, self.m))[i]\n j = tuple(range(self.m))[j]\n return Array2dView(self.arr, i, j)\n\n def get_ind(self, i, j):\n return i*self.m+j\n\n def __getitem__(self, index):\n try:\n return self.arr[self.get_ind(*index)]\n except TypeError:\n return self._get_view(*index)\n \n def __setitem__(self, index, value):\n try:\n self.arr[self.get_ind(*index)] = value\n except TypeError:\n x = self._get_view(*index)\n for i in x.i_indices:\n for j in x.j_indices:\n self.arr[i+j] = value\n \n def __iter__(self):\n return iter(self.arr)\n \n def __reversed__(self):\n return reversed(self.arr)\n \n def __str__(self):\n m = max(len(str(v)) for v in self)\n res = ['']*self.n\n row = ['']*(self.m+2)\n for i in range(self.n):\n if i == 0:\n row[0] = '['\n else:\n row[0] = ' '\n if i == self.n-1:\n row[-1] = ']\\n'\n for j in range(self.m):\n row[j+1] = f'{str(self.arr[i*self.m+j]):>{m+1}}'\n res[i] = ''.join(row)\n return '\\n'.join(res)\n\n __repr__ = __str__\n\n def __eq__(self, other):\n return self.arr == other.arr\n\n def copy(self):\n return self.__class__(self.n, self.m, self.arr[:])\n\n @property\n def t(self):\n arr = [self.arr[0]]*(len(self.arr))\n x = 0\n for i in range(self.n):\n for j in range(self.m):\n arr[j*self.n + i] = self.arr[x]\n x += 1\n return self.__class__(self.m, self.n, arr)\n"), 'lib.array3d': (False, 'class Array3d(list):\n def __init__(self, n, m, p, arr):\n list.__init__(self, arr)\n self.n = n\n self.m = m\n self.p = p\n self.mp = m*p\n\n @classmethod\n def full(cls, n, m, p, fill_value):\n return cls(n, m, p, [fill_value] * (n * m * p))\n\n def get_ind(self, i, j, k):\n return i * self.mp + j * self.p + k\n\n def __getitem__(self, index):\n return list.__getitem__(self, self.get_ind(*index))\n\n def __setitem__(self, index, value):\n list.__setitem__(self, self.get_ind(*index), value)\n'), 'lib.benchmark': (False, '\nfrom time import perf_counter as timer\ndef simple_timeit(func, repeat=1000, warmup=100):\n for i in range(warmup):\n func(i)\n start = timer()\n for i in range(repeat):\n func(i)\n stop = timer()\n return stop-start\n'), 'lib.data_structure': (False, 'from typing import List, Any, TypeVar, Iterator\nfrom collections.abc import MutableSet\n\nclass DisjointSet:\n def __init__(self, parent):\n self.parent = parent\n\n @classmethod\n def empty(cls, size):\n return cls([-1]*size)\n\n def find(self, x):\n stack = []\n while self.parent[x] >= 0:\n stack.append(x)\n x = self.parent[x]\n for y in stack:\n self.parent[y] = x\n return x\n\n def union_reps(self, xr, yr):\n if xr == yr:\n return xr\n if self.parent[xr] > self.parent[yr]:\n xr, yr = yr, xr\n self.parent[xr] += self.parent[yr]\n self.parent[yr] = xr\n return xr\n\n def union(self, x, y):\n return self.union_reps(self.find(x), self.find(y))\n\n def group_size(self, x):\n return -self.parent[self.find(x)]\n\n def is_rep(self, x):\n return self.parent[x] < 0\n\n def copy(self):\n return DisjointSet(self.parent)\n\n\nclass SegmentTree:\n """\n ???????????????????????????????????\n ???????????????????????????(???????????)\n """\n\n @classmethod\n def all_identity(cls, operator, identity, size):\n return cls(operator, identity, [identity] * (2 << (size - 1).bit_length()))\n\n @classmethod\n def from_initial_data(cls, operator, identity, data):\n size = 1 << (len(data) - 1).bit_length()\n temp = [identity] * (2 * size)\n temp[size:size + len(data)] = data\n data = temp\n\n for i in reversed(range(size)):\n data[i] = operator(data[2 * i], data[2 * i + 1])\n return cls(operator, identity, data)\n\n # ??????????????????????\n def __init__(self, operator, identity, data):\n self.op = operator\n self.id = identity\n self.data = data\n self.size = len(data) // 2\n\n def reduce(self, l, r):\n l += self.size\n r += self.size\n vl = self.id\n vr = self.id\n\n while l < r:\n if l & 1:\n vl = self.op(vl, self.data[l])\n l += 1\n if r & 1:\n r -= 1\n vr = self.op(self.data[r], vr)\n l >>= 1\n r >>= 1\n return self.op(vl, vr)\n\n def elements(self, l, r):\n l += self.size\n r += self.size\n\n lefts = []\n rights = []\n\n while l < r:\n if l & 1:\n lefts.append(self.data[l])\n l += 1\n if r & 1:\n r -= 1\n rights.append(self.data[r])\n l >>= 1\n r >>= 1\n return lefts, rights\n\n def __getitem__(self, i):\n if isinstance(i, slice):\n return self.reduce(\n 0 if i.start is None else i.start,\n self.size if i.stop is None else i.stop)\n elif isinstance(i, int):\n return self.data[i + self.size]\n\n def __setitem__(self, i, v):\n i += self.size\n while i:\n self.data[i] = v\n v = self.op(self.data[i ^ 1], v) if i & 1 else self.op(v, self.data[i ^ 1])\n i >>= 1\n\n def __iter__(self):\n return iter(self.data[self.size:])\n\n\nclass LazySegmentTree:\n """\n op: ????????reduce?????????\n apply: ??????\n comp: ??????\n \n range_query: reduce(op, (apply(x,m) for x,m in zip(X,M)))\n \n ???????:\n \n ??X (??)\n op[+]: X,X -> X\n (X, op)?????\n \n ??M (???)\n comp[*]: M,M -> M\n (M, compose)?????\n \n apply[f(x,m,n)]: X,M,Z+ -> X\n (Z+????)\n \n f(x,e_M,n) = x\n f(x,m*n,p) = f(f(x,m,p),n,p)\n f(x,m,p)+f(y,m,q) = f(x+y,m,p+q)\n \n ??: https://algo-logic.info/segment-tree/#toc_id_3\n """\n\n @classmethod\n def all_identity(cls, op, op_e, comp, comp_e, apply, size):\n size = 1 << (size - 1).bit_length()\n return cls(\n op,\n op_e,\n comp,\n comp_e,\n apply,\n [op_e] * (2 * size),\n [comp_e] * size\n )\n\n @classmethod\n def from_initial_data(cls, op, op_e, comp, comp_e, apply, data):\n size = 1 << (len(data) - 1).bit_length()\n temp = [op_e] * (2 * size)\n temp[size:size + len(data)] = data\n\n for i in reversed(range(size)):\n temp[i] = op(temp[2 * i], temp[2 * i + 1])\n return cls(\n op,\n op_e,\n comp,\n comp_e,\n apply,\n temp,\n [comp_e] * size\n )\n\n # ??????????????????????\n def __init__(self, op, op_e, comp, comp_e, apply, data, lazy):\n self.op = op\n self.op_e = op_e\n self.comp = comp\n self.comp_e = comp_e\n self.apply = apply\n self.data = data\n self.lazy = lazy\n self.size = len(self.data) // 2\n self.depth = self.size.bit_length() - 1\n self._l_indices = [0] * self.depth\n self._r_indices = [0] * self.depth\n\n def _update_indices(self, i, l):\n m = i // (i & -i)\n i >>= 1\n for k in range(self.depth):\n l[k] = i if i < m else 0\n i >>= 1\n\n def _propagate_top_down(self):\n data = self.data\n lazy = self.lazy\n apply = self.apply\n comp = self.comp\n comp_e = self.comp_e\n k = self.size >> 1\n\n for i, j in zip(reversed(self._l_indices), reversed(self._r_indices)):\n if i > 0:\n temp = lazy[i]\n if temp != comp_e:\n lazy[i] = comp_e\n a = i << 1\n b = a | 1\n data[a] = apply(data[a], temp, k)\n data[b] = apply(data[b], temp, k)\n if k > 1:\n lazy[a] = comp(lazy[a], temp)\n lazy[b] = comp(lazy[b], temp)\n if i < j:\n temp = lazy[j]\n if temp != comp_e:\n lazy[j] = comp_e\n a = j << 1\n b = a | 1\n data[a] = apply(data[a], temp, k)\n data[b] = apply(data[b], temp, k)\n if k > 1:\n lazy[a] = comp(lazy[a], temp)\n lazy[b] = comp(lazy[b], temp)\n k >>= 1\n\n def _propagate_bottom_up(self):\n data = self.data\n op = self.op\n for i, j in zip(self._l_indices, self._r_indices):\n if i < j:\n data[j] = op(data[j << 1], data[j << 1 | 1])\n if i > 0:\n data[i] = op(data[i << 1], data[i << 1 | 1])\n\n def update_interval(self, l, r, m):\n lazy = self.lazy\n data = self.data\n comp = self.comp\n apply = self.apply\n\n l += self.size\n r += self.size\n self._update_indices(l, self._l_indices)\n self._update_indices(r, self._r_indices)\n self._propagate_top_down()\n k = 1\n while l < r:\n if l & 1:\n data[l] = apply(data[l], m, k)\n if k > 1:\n lazy[l] = comp(lazy[l], m)\n l += 1\n if r & 1:\n r -= 1\n data[r] = apply(data[r], m, k)\n if k > 1:\n lazy[r] = comp(lazy[r], m)\n l >>= 1\n r >>= 1\n k <<= 1\n self._propagate_bottom_up()\n\n def get_interval(self, l, r):\n data = self.data\n op = self.op\n\n l += self.size\n r += self.size\n self._update_indices(l, self._l_indices)\n self._update_indices(r, self._r_indices)\n self._propagate_top_down()\n\n lx = self.op_e\n rx = self.op_e\n while l < r:\n if l & 1:\n lx = op(lx, data[l])\n l += 1\n if r & 1:\n r -= 1\n rx = op(data[r], rx)\n l >>= 1\n r >>= 1\n return op(lx, rx)\n\n\nfrom operator import add, sub\n\n\nclass BinaryIndexedTree:\n def __init__(self, size, zero=0, operator=add, inv_operator=sub):\n self.zero = zero\n self.op = operator\n self.inv = inv_operator\n self.data = [zero] * (size + 1)\n self.msb = 1 << (size.bit_length() - 1)\n\n def _add(self, i, w):\n i += 1\n while i < len(self.data):\n self.data[i] = self.op(self.data[i], w)\n i += i & -i\n\n def _get_sum(self, i):\n res = self.zero\n while i > 0:\n res = self.op(res, self.data[i])\n i -= i & -i\n return res\n\n def __getitem__(self, i):\n """\n [0,i)\n """\n if isinstance(i, slice):\n a = self._get_sum(len(self.data) - 1 if i.stop is None else i.stop)\n b = self._get_sum(0 if i.start is None else i.start)\n return self.inv(a, b)\n else:\n return self.zero # fake value\n\n __setitem__ = _add\n\n def bisect_left(self, v):\n """\n return smallest i s.t v <= sum[:i+1]\n """\n i = 0\n k = self.msb\n l = len(self.data)\n while k > 0:\n i += k\n if i < l and self.data[i] < v:\n v -= self.data[i]\n else:\n i -= k\n k >>= 1\n return i\n\n def bisect_right(self, v):\n """\n return smallest i s.t v < sum[:i+1]\n """\n i = 0\n k = self.msb\n l = len(self.data)\n while k > 0:\n i += k\n if i < l and self.data[i] <= v:\n v -= self.data[i]\n else:\n i -= k\n k >>= 1\n return i\n\n bisect = bisect_right\n\n\nimport bisect\nT = TypeVar(\'T\')\n\n\nclass SortedList(MutableSet):\n\n def __init__(self, sorted_values: List[T]):\n self.i2v = sorted_values\n self.v2i = {v:i for i,v in enumerate(self.i2v)}\n self.fen = BinaryIndexedTree(len(self.i2v))\n self.n = 0\n\n def rank(self, x:T) -> int:\n \'\'\'\n x???????????\n\n :param x: ??????\n :return: x????????\n \'\'\'\n return self.fen[:bisect.bisect_left(self.i2v, x)]\n\n def get(self, rank: int) -> T:\n return self.i2v[self.fen.bisect_left(rank)]\n\n def lower_bound(self, x: T, k: int = 1) -> T:\n \'\'\'\n x???k????????????O(log N)\n\n :param x: ??????\n :param k: ?????????????????1?\n :return: x???k????????\n \'\'\'\n t = self.fen[:bisect.bisect(self.i2v, x)]-k\n if t < 0 or t >= self.n:\n raise IndexError\n return self.fen.bisect_left(t)\n\n def upper_bound(self, x: T, k: int = 1) -> T:\n \'\'\'\n x???k????????????O(log N)\n\n :param x: ??????\n :param k: ?????????????????1?\n :return: x???k????????\n \'\'\'\n t = self.fen[:bisect(self.i2v, x)-1]+k\n if t < 0 or t >= self.n:\n raise IndexError\n return self.fen.bisect_left(t)\n\n def add(self, value: T) -> None:\n pass\n\n def discard(self, value: T) -> None:\n pass\n\n def __contains__(self, x: Any) -> bool:\n pass\n\n def __len__(self) -> int:\n pass\n\n def __iter__(self) -> Iterator[T]:\n pass\n\n\n\nclass SlidingWindowAggregator:\n # ????????\n def __init__(self, op, identity):\n self.op = op\n self.identity = identity\n self.data = []\n self.front = [identity]\n self.back = [identity]\n\n def __len__(self):\n return len(self.front) + len(self.back) - 2\n\n def push(self, x):\n self.data.append(x)\n self.back.append(self.op(self.back[-1], x))\n\n def pop(self):\n if len(self.front) == 1:\n self.move()\n self.front.pop()\n\n def move(self):\n self.back = [self.identity]\n for x in reversed(self.data):\n self.front.append(self.op(x, self.front[-1]))\n self.data.clear()\n\n def get(self):\n return self.op(self.front[-1], self.back[-1])\n\n# bit = BinaryIndexedTree(4)\n# bit[1] += 1\n# bit[2] += 1\n# for i in range(5):\n# print(i, bit.bisect_left(i), bit.bisect_right(i))'), 'lib.graph': (False, 'import itertools\nimport heapq as hq\nfrom lib.misc import min2\nfrom lib.array2d import Array2d\nfrom collections import defaultdict\n\nfrom typing import *\n\nT = TypeVar(\'T\')\n\nINF = 2 ** 62\n\n\nclass BaseWeightedGraph:\n\n def __init__(self, n_vertices: int):\n self.n_vertices = n_vertices\n\n def wadj(self, v: int) -> Iterable[Tuple[int, Any]]:\n """\n Return an iterable of vertices adjacent to v and edge weight\n """\n raise NotImplementedError\n\n def adj(self, v: int) -> Iterable[int]:\n """\n Return an iterable of vertices adjacent to v\n """\n return (u for u, w in self.wadj(v))\n\n @property\n def wedges(self) -> Iterable[Tuple[int, int, Any]]:\n """\n Return an iterable of weighted edges (vertex_1, vertex_2, weight)\n """\n return ((v, u, w) for v in range(self.n_vertices) for u, w in self.wadj(v))\n\n @property\n def edges(self):\n return ((v, u) for v in range(self.n_vertices) for u in self.adj(v))\n\n def dist(self, s: int, t: int, inf=INF):\n return dijkstra(self, s, t, inf)[t]\n\n def warshall_floyd(self, inf=INF):\n dist = Array2d.full(self.n_vertices, self.n_vertices, inf)\n for u, v, w in self.wedges:\n dist[u, v] = w\n for i in range(self.n_vertices):\n dist[i, i] = 0\n for k in range(self.n_vertices):\n for i in range(self.n_vertices):\n for j in range(self.n_vertices):\n dist[i, j] = min2(dist[i, j], dist[i, k] + dist[k, j])\n return dist\n\n def to_wgraph(self) -> \'WeightedGraph\':\n return WeightedGraph.from_directed_edges(self.n_vertices, self.wedges)\n\n def to_reverse_wgraph(self) -> \'WeightedGraph\':\n return WeightedGraph.from_directed_edges(self.n_vertices, ((u, v, w) for v, u, w in self.wedges))\n\n def to_graph(self) -> \'Graph\':\n l = [[] for _ in range(self.n_vertices)]\n for u, v in self.edges:\n l[u].append(v)\n return Graph.from_lil_adj(self.n_vertices, l)\n\n def to_reverse_graph(self) -> \'Graph\':\n l = [[] for _ in range(self.n_vertices)]\n for u, v in self.edges:\n l[v].append(u)\n return Graph.from_lil_adj(self.n_vertices, l)\n\n\nclass WeightedGraph(BaseWeightedGraph):\n\n def __init__(self, n_vertices: int, adj: List[int], weight: List[Any], ind: List[int]):\n super().__init__(n_vertices)\n self._adj = adj\n self._weight = weight\n self._ind = ind\n\n @classmethod\n def from_lil_adj(cls, n_vertices: int, adj_list: Iterable[Sequence[Tuple[int, Any]]],\n n_edges: int) -> \'WeightedGraph\':\n adj = [0] * n_edges\n weight = [0] * n_edges\n ind = [0] * (n_vertices + 1)\n i = 0\n for u, l in enumerate(adj_list):\n ind[u] = i\n for v, w in l:\n adj[i] = v\n weight[i] = w\n i += 1\n ind[n_vertices] = i\n return cls(n_vertices, adj, weight, ind)\n\n @classmethod\n def from_directed_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int, int]]) -> \'WeightedGraph\':\n temp = [[] for _ in range(n_vertices)]\n n_edges = 0\n for u, v, w in edges:\n temp[u].append((v, w))\n n_edges += 1\n return cls.from_lil_adj(n_vertices, temp, n_edges)\n\n @classmethod\n def from_undirected_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int, int]]) -> \'WeightedGraph\':\n return cls.from_directed_edges(n_vertices, itertools.chain(edges, ((u, v, w) for v, u, w in edges)))\n\n def wadj(self, v: int) -> Iterable[Tuple[int, Any]]:\n i, j = self._ind[v], self._ind[v + 1]\n return ((self._adj[k], self._weight[k]) for k in range(i, j))\n\n\nclass ModifiableWeightedGraph(BaseWeightedGraph):\n\n def __init__(self, n_vertices: int, edges: MutableMapping[Tuple[int, int], Any]):\n super().__init__(n_vertices)\n self._edges = edges\n temp = [set() for _ in range(n_vertices)]\n for u, v, w in edges:\n temp[u].add((v, w))\n self._adj = temp\n\n @classmethod\n def from_directed_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int, Any]]) -> \'ModifiableWeightedGraph\':\n return cls(n_vertices, edges)\n\n @classmethod\n def from_undirected_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int, Any]]) -> \'ModifiableWeightedGraph\':\n return cls.from_directed_edges(n_vertices, itertools.chain(edges, ((u, v, w) for v, u, w in edges)))\n\n def wadj(self, v: int) -> Iterable[Tuple[int, Any]]:\n return self._adj[v]\n\n def update_edge(self, v: int, u: int, w: Any) -> None:\n try:\n w_old = self._edges[v, u]\n self._edges[v, u] = w\n self._adj[v].discard((u, w_old))\n self._adj[v].add((u, w))\n except KeyError:\n self._edges[v, u] = w\n self._adj[v].add((u, w))\n\n def delete_edge(self, v: int, u: int) -> None:\n try:\n w = self._edges[v, u]\n del self._edges[v, u]\n self._adj[v].discard((u, w))\n except KeyError:\n pass\n\n\nclass BaseGraph(BaseWeightedGraph):\n\n def adj(self, v):\n raise NotImplementedError\n\n def wadj(self, v):\n return ((u, 1) for u in self.adj(v))\n\n def dist(self, s: int, t: int, inf: Any = INF):\n d = self.bfs(s, t)[t]\n return inf if d == -1 else d\n\n def furthest_vertex(self, v0):\n """\n Returns a vertex that is furthest away from v0, and its distance from v0\n """\n q = [v0]\n visited = [0] * self.n_vertices\n visited[v0] = 1\n x = -1\n rd = 0\n for d in itertools.count():\n if not q:\n rd = d\n break\n x = q[0]\n nq = []\n for v in q:\n for u in self.adj(v):\n if not visited[u]:\n visited[u] = 1\n nq.append(u)\n q = nq\n return x, rd\n\n\nclass Graph(BaseGraph):\n\n def __init__(self, n_vertices: int, adj: List[int], ind: List[int]):\n super().__init__(n_vertices)\n self._adj = adj\n self._ind = ind\n\n @classmethod\n def from_lil_adj(cls, n_vertices: int, adj_list: Iterable[Sequence[int]]) -> \'Graph\':\n n_edges = sum(len(l) for l in adj_list)\n adj = [0] * n_edges\n ind = [0] * (n_vertices + 1)\n i = 0\n for u, l in enumerate(adj_list):\n ind[u] = i\n for v in l:\n adj[i] = v\n i += 1\n ind[n_vertices] = i\n return cls(n_vertices, adj, ind)\n\n @classmethod\n def from_directed_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int]]) -> \'Graph\':\n temp = [[] for _ in range(n_vertices)]\n for u, v in edges:\n temp[u].append(v)\n return cls.from_lil_adj(n_vertices, temp)\n\n @classmethod\n def from_undirected_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int]]) -> \'Graph\':\n temp = [[] for _ in range(n_vertices)]\n for u, v in edges:\n temp[u].append(v)\n temp[v].append(u)\n return cls.from_lil_adj(n_vertices, temp)\n\n def adj(self, v):\n return self._adj[self._ind[v]: self._ind[v + 1]]\n\n\nclass ModifiableGraph(BaseGraph):\n\n def __init__(self, n_vertices: int, adj: List[MutableSet[int]]):\n super().__init__(n_vertices)\n self._adj = adj\n\n @classmethod\n def from_directed_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int]]) -> \'ModifiableGraph\':\n temp = [set() for _ in range(n_vertices)]\n for u, v in edges:\n temp[u].add(v)\n return cls(n_vertices, temp)\n\n @classmethod\n def from_undirected_edges(cls, n_vertices: int, edges: Iterable[Tuple[int, int]]) -> \'ModifiableGraph\':\n return cls.from_directed_edges(n_vertices, itertools.chain(edges, ((u, v) for v, u in edges)))\n\n def adj(self, v: int) -> Iterable[int]:\n return self._adj[v]\n\n def add_edge(self, v: int, u: int) -> None:\n self._adj[v].add(u)\n\n def delete_edge(self, v: int, u: int) -> None:\n self._adj[v].discard(u)\n\n\nclass FunctionalGraph(BaseGraph):\n def __init__(self, n_vertices: int, func: List[int]):\n super().__init__(n_vertices)\n self.func = func\n\n def adj(self, v: int) -> Iterable[int]:\n yield self.func[v]\n\n def get_doubling(self, max_length: int) -> Array2d:\n k = max_length.bit_length()\n dbl = Array2d.full(k, self.n_vertices, 0)\n for v in range(self.n_vertices):\n dbl[0, v] = self.func[v]\n for t in range(1, k):\n for v in range(self.n_vertices):\n dbl[t, v] = dbl[t-1, dbl[t-1, v]]\n return dbl\n\n @staticmethod\n def apply_func(v: int, k: int, dbl: Array2d) -> int:\n assert k.bit_length() <= dbl.n\n\n for t in range(dbl.n):\n if k&1:\n v = dbl[t, v]\n k >>= 1\n return v\n\n\nclass Grid(BaseGraph):\n def __init__(self, grid):\n super().__init__(grid.n * grid.m)\n self.grid = grid\n\n def adj(self, v):\n if not self.grid.arr[v]:\n return\n i, j = divmod(v, self.grid.m)\n if i + 1 < self.grid.n and self.grid[i + 1, j]:\n yield v + self.grid.m\n if 0 <= i - 1 and self.grid[i - 1, j]:\n yield v - self.grid.m\n if j + 1 < self.grid.m and self.grid[i, j + 1]:\n yield v + 1\n if 0 <= j - 1 and self.grid[i, j - 1]:\n yield v - 1\n\n\ndef strongly_connected_components(graph: BaseWeightedGraph, rgraph: BaseWeightedGraph = None):\n if rgraph is None:\n rgraph = graph.to_reverse_graph()\n n = graph.n_vertices\n order = []\n color = [0] * n\n for v0 in range(n):\n if color[v0]:\n continue\n color[v0] = -1\n stack = [iter(graph.adj(v0))]\n path = [v0]\n while path:\n for u in stack[-1]:\n if color[u] == 0:\n color[u] = -1\n path.append(u)\n stack.append(iter(graph.adj(u)))\n break\n else:\n v = path.pop()\n order.append(v)\n stack.pop()\n\n label = 0\n for v0 in reversed(order):\n if color[v0] >= 0:\n continue\n color[v0] = label\n stack = [v0]\n while stack:\n v = stack.pop()\n for u in rgraph.adj(v):\n if color[u] < 0:\n color[u] = label\n stack.append(u)\n label += 1\n return label, color\n\n\ndef bfs(graph: BaseWeightedGraph, s: Union[int, Iterable[int]], t: Union[int, Iterable[int]] = -1) -> List[int]:\n """\n ?????????????????\n\n :param graph: ???\n :param s: ????\n :param t: ????\n :return: ?????(s??????????-1)\n """\n dist = [-1] * graph.n_vertices\n\n if isinstance(s, int):\n q = [s]\n dist[s] = 0\n else:\n q = list(s)\n for v in q:\n dist[v] = 0\n\n if isinstance(t, int):\n t = [t]\n else:\n t = list(t)\n if len(t) > 8:\n t = set(t)\n\n for d in range(1, graph.n_vertices):\n nq = []\n for v in q:\n for u in graph.adj(v):\n if dist[u] < 0:\n dist[u] = d\n nq.append(u)\n if u in t:\n return dist\n q = nq\n return dist\n\n\ndef dijkstra(graph: BaseWeightedGraph, s: Union[int, Iterable[int]], t: Union[int, Iterable[int]] = -1,\n inf: int = INF) -> List[int]:\n """\n Returns a list of distance. If starts contains more than one vertex, returns the shortest distance from any of them.\n """\n K = graph.n_vertices.bit_length()\n MASK = (1 << K) - 1\n dist = [inf] * graph.n_vertices\n\n if isinstance(s, int):\n q = [s]\n dist[s] = 0\n else:\n q = list(s)\n for v in q:\n dist[v] = 0\n if isinstance(t, int):\n if t < 0:\n t = []\n else:\n t = [t]\n else:\n t = set(t)\n\n while q:\n x = hq.heappop(q)\n d, v = x >> K, x & MASK\n if v in t:\n return dist\n if d > dist[v]:\n continue\n for u, w in graph.wadj(v):\n if dist[u] > d + w:\n dist[u] = d + w\n hq.heappush(q, ((d + w) << K) | u)\n return dist\n\n\ndef dijkstra_general(graph: BaseWeightedGraph, inf: T, zero: T, s: Union[int, Iterable[int]],\n t: Union[int, Iterable[int]] = -1) -> List[Any]:\n """\n Returns a list of distance. If starts contains more than one vertex, returns the shortest distance from any of them.\n """\n dist = [inf] * graph.n_vertices\n\n if isinstance(s, int):\n q = [(zero, s)]\n dist[s] = zero\n else:\n q = [(zero, v) for v in s]\n for d, v in q:\n dist[v] = zero\n if isinstance(t, int):\n if t < 0:\n t = []\n else:\n t = [t]\n else:\n t = set(t)\n\n while q:\n d, v = hq.heappop(q)\n if v in t:\n return dist\n if d > dist[v]:\n continue\n for u, w in graph.wadj(v):\n nw = d + w\n if dist[u] > nw:\n dist[u] = nw\n hq.heappush(q, (nw, u))\n return dist\n\n\ndef get_dual_graph(n_vertices: int, wedges: Iterable[Tuple[int, int, int]]) -> Tuple[\n List[int], List[int], List[int], List[int]]:\n """\n ?????????????????\n\n (u, v, cap) in E ??????????? (u, v, cap) ? (v, u, 0) ?????????????????????????\n\n :param n_vertices: ???\n :param wedges: ?????\n :return: (???????, ???index?????)\n """\n\n cap = defaultdict(int)\n for u, v, c in wedges:\n cap[(u, v)] += c\n cap[(v, u)] += 0\n temp: List[List[Tuple[int, int]]] = [[] for _ in range(n_vertices)]\n for (u, v), w in cap.items():\n temp[u].append((v, w))\n\n adj = [0] * len(cap)\n weight = [0] * len(cap)\n rev = [0] * len(cap)\n ind = [0] * (n_vertices + 1)\n\n i = 0\n for u, l in enumerate(temp):\n ind[u] = i\n for v, w in l:\n adj[i] = v\n weight[i] = w\n if u < v:\n cap[(v, u)] = i\n else:\n j = cap[(u, v)]\n rev[i] = j\n rev[j] = i\n i += 1\n ind[n_vertices] = i\n\n return adj, weight, ind, rev\n\n\ndef edmonds_karp(n_vertices: int, edges: Iterable[Tuple[int, int, int]], s: int, t: int):\n """\n ????????\n\n ???: ``O(VE^2)``\n\n :param n_vertices: ???\n :param edges: (??1, ??2, ??)?Iterable\n :param s: ??\n :param t: ??\n :return: (????, ?????, ?????)\n """\n\n adj, caps, ind, rev = get_dual_graph(n_vertices, edges)\n\n m0 = max(caps)\n bfs_memo = [0] * n_vertices\n pv = [-1] * n_vertices\n pe = [-1] * n_vertices\n bfs_memo[s] = n_vertices + 1\n offset = 0\n\n def find_path():\n nonlocal offset\n offset += 1\n q = [s]\n while q:\n nq = []\n for v in q:\n if v == t:\n return True\n for i in range(ind[v], ind[v + 1]):\n if caps[i] == 0:\n continue\n u = adj[i]\n if bfs_memo[u] < offset:\n bfs_memo[u] = offset\n pv[u] = v\n pe[u] = i\n nq.append(u)\n q = nq\n return False\n\n res = 0\n flag = find_path()\n while flag:\n v = t\n m = m0\n while pv[v] >= 0:\n e = pe[v]\n m = min2(m, caps[e])\n v = pv[v]\n v = t\n while pv[v] >= 0:\n e = pe[v]\n caps[e] -= m\n caps[rev[e]] += m\n v = pv[v]\n res += m\n flag = find_path()\n return res, WeightedGraph(n_vertices, adj, caps, ind), rev\n\n\ndef min_st_cut(n_vertices: int, edges: Iterable[Tuple[int, int, int]], s: int, t: int):\n """\n ?? ``st`` ?????????\n\n :param n_vertices: ???\n :param edges: ?\n :param s: ??\n :param t: ??\n :return: (?????, ???????(0-1??????), ?????, ?????)\n """\n flow, g, rev = edmonds_karp(n_vertices, edges, s, t)\n stack = [s]\n visited = [0] * n_vertices\n visited[s] = 1\n while stack:\n v = stack.pop()\n for u, w in g.wadj(v):\n if w > 0 and not visited[u]:\n stack.append(u)\n visited[u] = 1\n return flow, visited, g, rev\n\n\nclass MaxFlowGraph:\n class Edge(NamedTuple):\n src: int\n dst: int\n cap: int\n flow: int\n\n class _Edge:\n def __init__(self, dst: int, cap: int) -> None:\n self.dst = dst\n self.cap = cap\n self.rev: Optional[MaxFlowGraph._Edge] = None\n\n def __init__(self, n: int) -> None:\n self._n = n\n self._g: List[List[MaxFlowGraph._Edge]] = [[] for _ in range(n)]\n self._edges: List[MaxFlowGraph._Edge] = []\n\n def add_edge(self, src: int, dst: int, cap: int) -> int:\n assert 0 <= src < self._n\n assert 0 <= dst < self._n\n assert 0 <= cap\n m = len(self._edges)\n e = MaxFlowGraph._Edge(dst, cap)\n re = MaxFlowGraph._Edge(src, 0)\n e.rev = re\n re.rev = e\n self._g[src].append(e)\n self._g[dst].append(re)\n self._edges.append(e)\n return m\n\n def get_edge(self, i: int) -> Edge:\n assert 0 <= i < len(self._edges)\n e = self._edges[i]\n re = cast(MaxFlowGraph._Edge, e.rev)\n return MaxFlowGraph.Edge(\n re.dst,\n e.dst,\n e.cap + re.cap,\n re.cap\n )\n\n def edges(self) -> List[Edge]:\n return [self.get_edge(i) for i in range(len(self._edges))]\n\n def change_edge(self, i: int, new_cap: int, new_flow: int) -> None:\n assert 0 <= i < len(self._edges)\n assert 0 <= new_flow <= new_cap\n e = self._edges[i]\n e.cap = new_cap - new_flow\n assert e.rev is not None\n e.rev.cap = new_flow\n\n def flow(self, s: int, t: int, flow_limit: Optional[int] = None) -> int:\n assert 0 <= s < self._n\n assert 0 <= t < self._n\n assert s != t\n if flow_limit is None:\n flow_limit = cast(int, sum(e.cap for e in self._g[s]))\n\n current_edge = [0] * self._n\n level = [0] * self._n\n\n def fill(arr: List[int], value: int) -> None:\n for i in range(len(arr)):\n arr[i] = value\n\n def bfs() -> bool:\n fill(level, self._n)\n queue = []\n q_front = 0\n queue.append(s)\n level[s] = 0\n while q_front < len(queue):\n v = queue[q_front]\n q_front += 1\n next_level = level[v] + 1\n for e in self._g[v]:\n if e.cap == 0 or level[e.dst] <= next_level:\n continue\n level[e.dst] = next_level\n if e.dst == t:\n return True\n queue.append(e.dst)\n return False\n\n def dfs(lim: int) -> int:\n stack = []\n edge_stack: List[MaxFlowGraph._Edge] = []\n stack.append(t)\n while stack:\n v = stack[-1]\n if v == s:\n flow = min(lim, min(e.cap for e in edge_stack))\n for e in edge_stack:\n e.cap -= flow\n assert e.rev is not None\n e.rev.cap += flow\n return flow\n next_level = level[v] - 1\n while current_edge[v] < len(self._g[v]):\n e = self._g[v][current_edge[v]]\n re = cast(MaxFlowGraph._Edge, e.rev)\n if level[e.dst] != next_level or re.cap == 0:\n current_edge[v] += 1\n continue\n stack.append(e.dst)\n edge_stack.append(re)\n break\n else:\n stack.pop()\n if edge_stack:\n edge_stack.pop()\n level[v] = self._n\n return 0\n\n flow = 0\n while flow < flow_limit:\n if not bfs():\n break\n fill(current_edge, 0)\n while flow < flow_limit:\n f = dfs(flow_limit - flow)\n flow += f\n if f == 0:\n break\n return flow\n\n def min_cut(self, s: int) -> List[bool]:\n visited = [False] * self._n\n stack = [s]\n visited[s] = True\n while stack:\n v = stack.pop()\n for e in self._g[v]:\n if e.cap > 0 and not visited[e.dst]:\n visited[e.dst] = True\n stack.append(e.dst)\n return visited\n\n\nclass MinCostFlowGraph:\n class Edge(NamedTuple):\n src: int\n dst: int\n cap: int\n flow: int\n cost: int\n\n class _Edge:\n def __init__(self, dst: int, cap: int, cost: int) -> None:\n self.dst = dst\n self.cap = cap\n self.cost = cost\n self.rev: Optional[MinCostFlowGraph._Edge] = None\n\n def __init__(self, n: int) -> None:\n self._n = n\n self._g: List[List[MinCostFlowGraph._Edge]] = [[] for _ in range(n)]\n self._edges: List[MinCostFlowGraph._Edge] = []\n\n def add_edge(self, src: int, dst: int, cap: int, cost: int) -> int:\n assert 0 <= src < self._n\n assert 0 <= dst < self._n\n assert 0 <= cap\n m = len(self._edges)\n e = MinCostFlowGraph._Edge(dst, cap, cost)\n re = MinCostFlowGraph._Edge(src, 0, -cost)\n e.rev = re\n re.rev = e\n self._g[src].append(e)\n self._g[dst].append(re)\n self._edges.append(e)\n return m\n\n def get_edge(self, i: int) -> Edge:\n assert 0 <= i < len(self._edges)\n e = self._edges[i]\n re = cast(MinCostFlowGraph._Edge, e.rev)\n return MinCostFlowGraph.Edge(\n re.dst,\n e.dst,\n e.cap + re.cap,\n re.cap,\n e.cost\n )\n\n def edges(self) -> List[Edge]:\n return [self.get_edge(i) for i in range(len(self._edges))]\n\n def flow(self, s: int, t: int,\n flow_limit: Optional[int] = None) -> Tuple[int, int]:\n return self.slope(s, t, flow_limit)[-1]\n\n def slope(self, s: int, t: int,\n flow_limit: Optional[int] = None) -> List[Tuple[int, int]]:\n assert 0 <= s < self._n\n assert 0 <= t < self._n\n assert s != t\n if flow_limit is None:\n flow_limit = cast(int, sum(e.cap for e in self._g[s]))\n\n dual = [0] * self._n\n prev: List[Optional[Tuple[int, MinCostFlowGraph._Edge]]] = [None] * self._n\n\n def refine_dual() -> bool:\n pq = [(0, s)]\n visited = [False] * self._n\n dist: List[Optional[int]] = [None] * self._n\n dist[s] = 0\n while pq:\n dist_v, v = hq.heappop(pq)\n if visited[v]:\n continue\n visited[v] = True\n if v == t:\n break\n dual_v = dual[v]\n for e in self._g[v]:\n w = e.dst\n if visited[w] or e.cap == 0:\n continue\n reduced_cost = e.cost - dual[w] + dual_v\n new_dist = dist_v + reduced_cost\n dist_w = dist[w]\n if dist_w is None or new_dist < dist_w:\n dist[w] = new_dist\n prev[w] = v, e\n hq.heappush(pq, (new_dist, w))\n else:\n return False\n dist_t = dist[t]\n for v in range(self._n):\n if visited[v]:\n dual[v] -= cast(int, dist_t) - cast(int, dist[v])\n return True\n\n flow = 0\n cost = 0\n prev_cost_per_flow: Optional[int] = None\n result = [(flow, cost)]\n while flow < flow_limit:\n if not refine_dual():\n break\n f = flow_limit - flow\n v = t\n while prev[v] is not None:\n u, e = cast(Tuple[int, MinCostFlowGraph._Edge], prev[v])\n f = min(f, e.cap)\n v = u\n v = t\n while prev[v] is not None:\n u, e = cast(Tuple[int, MinCostFlowGraph._Edge], prev[v])\n e.cap -= f\n assert e.rev is not None\n e.rev.cap += f\n v = u\n c = -dual[s]\n flow += f\n cost += f * c\n if c == prev_cost_per_flow:\n result.pop()\n result.append((flow, cost))\n prev_cost_per_flow = c\n return result'), 'lib.itertools': (False, "from itertools import chain, repeat, count, islice\nfrom collections import Counter\n\n\ndef repeat_chain(values, counts):\n return chain.from_iterable(map(repeat, values, counts))\n\n\ndef unique_combinations_from_value_counts(values, counts, r):\n n = len(counts)\n indices = list(islice(repeat_chain(count(), counts), r))\n if len(indices) < r:\n return\n while True:\n yield tuple(values[i] for i in indices)\n for i, j in zip(reversed(range(r)), repeat_chain(reversed(range(n)), reversed(counts))):\n if indices[i] != j:\n break\n else:\n return\n j = indices[i] + 1\n for i, j in zip(range(i, r), repeat_chain(count(j), counts[j:])):\n indices[i] = j\n\n\ndef unique_combinations(iterable, r):\n values, counts = zip(*Counter(iterable).items())\n return unique_combinations_from_value_counts(values, counts, r)\n\n\nclass UniqueCombinations:\n def __init__(self, values, counts, r):\n self.values = values\n self.counts = counts\n self.r = r\n\n # dp[i][k] := # of unique combinations of length k or shorter with elements values[i:]\n dp = [[1]*(r+1) for c in range(len(counts)+1)]\n for i in reversed(range(len(counts))):\n cnt = self.counts[i]\n for k in range(1, r+1):\n dp[i][k] = dp[i][k-1] + dp[i+1][k] - (dp[i+1][k-cnt-1] if k >= cnt+1 else 0)\n self.dp = dp\n\n def __getitem__(self, ind):\n res = []\n for i in range(len(self.counts)):\n for k in reversed(range(1, min(self.r-len(res), self.counts[i])+1)):\n t = self.dp[i+1][self.r - len(res) - k]-(self.dp[i+1][self.r - len(res)-k-1] if self.r - len(res) >= k+1 else 0)\n if ind < t:\n res.extend(self.values[i] for _ in range(k))\n break\n else:\n ind -= t\n return tuple(res)\n\n def __len__(self):\n return self.dp[0][self.r] - self.dp[0][self.r-1]\n\n\n\nif __name__ == '__main__':\n uc = UniqueCombinations([1,2,3], [5,3,1], 4)\n for i in range(len(uc)):\n print(uc[i])\n # print(list(unique_combinations([2, 2, 2, 2, 4], 4)))\n # print(list(unique_combinations_from_value_counts('abc', [1, 2, 3], 3)))\n"), 'lib.matrix': (False, "from lib.array2d import Array2d\n\n\ndef get_general_matrix(zero, one):\n class Matrix(Array2d):\n ZERO = zero\n ONE = one\n\n @classmethod\n def zeros(cls, n, m):\n return cls.full(n, m, cls.ZERO)\n\n @classmethod\n def ones(cls, n, m):\n return cls.full(n, m, cls.ONE)\n\n def __add__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot add matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n return Matrix(self.n, self.m, [x + y for x, y in zip(self.arr, other.arr)])\n\n def __iadd__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n for i, v in enumerate(other.arr):\n self.arr[i] += v\n return self\n\n def __sub__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot subtract matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n return Matrix(self.n, self.m, [x - y for x, y in zip(self.arr, other.arr)])\n\n def __isub__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n for i, v in enumerate(other.arr):\n self.arr[i] -= v\n return self\n\n def __mul__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n return Matrix(self.n, self.m, [x * y for x, y in zip(self.arr, other.arr)])\n\n def __imul__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n for i, v in enumerate(other.arr):\n self.arr[i] *= v\n return self\n\n def __truediv__(self, other):\n if self.m != other.m or self.n != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n return Matrix(self.n, self.m, [x / y for x, y in zip(self.arr, other.arr)])\n\n def __matmul__(self, other):\n if self.m != other.n:\n raise ValueError(f'Cannot dot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n\n res = self.full(self.n, other.m, self.ZERO)\n\n for i in range(self.n):\n for j in range(other.m):\n c = self.ZERO\n for k in range(self.m):\n c += self[i, k] * other[k, j]\n res[i, j] = c\n return res\n\n def __imatmul__(self, other):\n if self.m != other.n:\n raise ValueError(f'Cannot multiply matrices ({self.n}, {self.m}) and ({other.n}, {other.m})')\n if self is other or self.m != other.m:\n return self @ other\n\n row = [self.ZERO] * self.m\n for i in range(self.n):\n t = i * self.m\n for j in range(self.m):\n row[j] = self.arr[j + t]\n for j in range(other.m):\n c = self.ZERO\n for k in range(self.m):\n c += row[k] * other[k, j]\n self[i, j] = c\n return self\n\n def __pow__(self, power, modulo=None):\n if self.n != self.m:\n raise ValueError('pow is supported only for square matrix')\n k = self.n\n res = Matrix.full(k, k, self.ZERO)\n for i in range(k):\n res[i, i] = self.ONE\n\n m = self\n while power > 0:\n if power & 1:\n res @= m\n m @= m\n power >>= 1\n return res\n\n return Matrix\n\n\nIMatrix = get_general_matrix(0, 1)\nFMatrix = get_general_matrix(0.0, 1.0)\n\n\ndef accumulate(mat):\n res = mat.zeros(mat.n + 1, mat.m + 1)\n for i in range(mat.n):\n k = mat.ZERO\n for j in range(mat.m):\n k += mat[i, j]\n res[i + 1, j + 1] = k\n for j in range(1, mat.m + 1):\n k = mat.ZERO\n for i in range(1, mat.n + 1):\n k += res[i, j]\n res[i, j] = k\n return res\n\n\ndef accumulate_prod(mat):\n res = mat.ones(mat.n + 1, mat.m + 1)\n for i in range(mat.n):\n k = mat.ONE\n for j in range(mat.m):\n k *= mat[i, j]\n res[i + 1, j + 1] = k\n for j in range(1, mat.m + 1):\n k = mat.ONE\n for i in range(1, mat.n):\n k *= res[i, j]\n res[i, j] = k\n return res\n"), 'lib.mincostflow': (False, 'from typing import NamedTuple, Optional, List, Tuple, cast\nfrom heapq import heappush, heappop\n\nclass MFGraph:\n class Edge(NamedTuple):\n src: int\n dst: int\n cap: int\n flow: int\n\n class _Edge:\n def __init__(self, dst: int, cap: int) -> None:\n self.dst = dst\n self.cap = cap\n self.rev: Optional[MFGraph._Edge] = None\n\n def __init__(self, n: int) -> None:\n self._n = n\n self._g: List[List[MFGraph._Edge]] = [[] for _ in range(n)]\n self._edges: List[MFGraph._Edge] = []\n\n def add_edge(self, src: int, dst: int, cap: int) -> int:\n assert 0 <= src < self._n\n assert 0 <= dst < self._n\n assert 0 <= cap\n m = len(self._edges)\n e = MFGraph._Edge(dst, cap)\n re = MFGraph._Edge(src, 0)\n e.rev = re\n re.rev = e\n self._g[src].append(e)\n self._g[dst].append(re)\n self._edges.append(e)\n return m\n\n def get_edge(self, i: int) -> Edge:\n assert 0 <= i < len(self._edges)\n e = self._edges[i]\n re = cast(MFGraph._Edge, e.rev)\n return MFGraph.Edge(\n re.dst,\n e.dst,\n e.cap + re.cap,\n re.cap\n )\n\n def edges(self) -> List[Edge]:\n return [self.get_edge(i) for i in range(len(self._edges))]\n\n def change_edge(self, i: int, new_cap: int, new_flow: int) -> None:\n assert 0 <= i < len(self._edges)\n assert 0 <= new_flow <= new_cap\n e = self._edges[i]\n e.cap = new_cap - new_flow\n assert e.rev is not None\n e.rev.cap = new_flow\n\n def flow(self, s: int, t: int, flow_limit: Optional[int] = None) -> int:\n assert 0 <= s < self._n\n assert 0 <= t < self._n\n assert s != t\n if flow_limit is None:\n flow_limit = cast(int, sum(e.cap for e in self._g[s]))\n\n current_edge = [0] * self._n\n level = [0] * self._n\n\n def fill(arr: List[int], value: int) -> None:\n for i in range(len(arr)):\n arr[i] = value\n\n def bfs() -> bool:\n fill(level, self._n)\n queue = []\n q_front = 0\n queue.append(s)\n level[s] = 0\n while q_front < len(queue):\n v = queue[q_front]\n q_front += 1\n next_level = level[v] + 1\n for e in self._g[v]:\n if e.cap == 0 or level[e.dst] <= next_level:\n continue\n level[e.dst] = next_level\n if e.dst == t:\n return True\n queue.append(e.dst)\n return False\n\n def dfs(lim: int) -> int:\n stack = []\n edge_stack: List[MFGraph._Edge] = []\n stack.append(t)\n while stack:\n v = stack[-1]\n if v == s:\n flow = min(lim, min(e.cap for e in edge_stack))\n for e in edge_stack:\n e.cap -= flow\n assert e.rev is not None\n e.rev.cap += flow\n return flow\n next_level = level[v] - 1\n while current_edge[v] < len(self._g[v]):\n e = self._g[v][current_edge[v]]\n re = cast(MFGraph._Edge, e.rev)\n if level[e.dst] != next_level or re.cap == 0:\n current_edge[v] += 1\n continue\n stack.append(e.dst)\n edge_stack.append(re)\n break\n else:\n stack.pop()\n if edge_stack:\n edge_stack.pop()\n level[v] = self._n\n return 0\n\n flow = 0\n while flow < flow_limit:\n if not bfs():\n break\n fill(current_edge, 0)\n while flow < flow_limit:\n f = dfs(flow_limit - flow)\n flow += f\n if f == 0:\n break\n return flow\n\n def min_cut(self, s: int) -> List[bool]:\n visited = [False] * self._n\n stack = [s]\n visited[s] = True\n while stack:\n v = stack.pop()\n for e in self._g[v]:\n if e.cap > 0 and not visited[e.dst]:\n visited[e.dst] = True\n stack.append(e.dst)\n return visited\n\nclass MCFGraph:\n class Edge(NamedTuple):\n src: int\n dst: int\n cap: int\n flow: int\n cost: int\n\n class _Edge:\n def __init__(self, dst: int, cap: int, cost: int) -> None:\n self.dst = dst\n self.cap = cap\n self.cost = cost\n self.rev: Optional[MCFGraph._Edge] = None\n\n def __init__(self, n: int) -> None:\n self._n = n\n self._g: List[List[MCFGraph._Edge]] = [[] for _ in range(n)]\n self._edges: List[MCFGraph._Edge] = []\n\n def add_edge(self, src: int, dst: int, cap: int, cost: int) -> int:\n assert 0 <= src < self._n\n assert 0 <= dst < self._n\n assert 0 <= cap\n m = len(self._edges)\n e = MCFGraph._Edge(dst, cap, cost)\n re = MCFGraph._Edge(src, 0, -cost)\n e.rev = re\n re.rev = e\n self._g[src].append(e)\n self._g[dst].append(re)\n self._edges.append(e)\n return m\n\n def get_edge(self, i: int) -> Edge:\n assert 0 <= i < len(self._edges)\n e = self._edges[i]\n re = cast(MCFGraph._Edge, e.rev)\n return MCFGraph.Edge(\n re.dst,\n e.dst,\n e.cap + re.cap,\n re.cap,\n e.cost\n )\n\n def edges(self) -> List[Edge]:\n return [self.get_edge(i) for i in range(len(self._edges))]\n\n def flow(self, s: int, t: int,\n flow_limit: Optional[int] = None) -> Tuple[int, int]:\n return self.slope(s, t, flow_limit)[-1]\n\n def slope(self, s: int, t: int,\n flow_limit: Optional[int] = None) -> List[Tuple[int, int]]:\n assert 0 <= s < self._n\n assert 0 <= t < self._n\n assert s != t\n if flow_limit is None:\n flow_limit = cast(int, sum(e.cap for e in self._g[s]))\n\n dual = [0] * self._n\n prev: List[Optional[Tuple[int, MCFGraph._Edge]]] = [None] * self._n\n\n def refine_dual() -> bool:\n pq = [(0, s)]\n visited = [False] * self._n\n dist: List[Optional[int]] = [None] * self._n\n dist[s] = 0\n while pq:\n dist_v, v = heappop(pq)\n if visited[v]:\n continue\n visited[v] = True\n if v == t:\n break\n dual_v = dual[v]\n for e in self._g[v]:\n w = e.dst\n if visited[w] or e.cap == 0:\n continue\n reduced_cost = e.cost - dual[w] + dual_v\n new_dist = dist_v + reduced_cost\n dist_w = dist[w]\n if dist_w is None or new_dist < dist_w:\n dist[w] = new_dist\n prev[w] = v, e\n heappush(pq, (new_dist, w))\n else:\n return False\n dist_t = dist[t]\n for v in range(self._n):\n if visited[v]:\n dual[v] -= cast(int, dist_t) - cast(int, dist[v])\n return True\n\n flow = 0\n cost = 0\n prev_cost_per_flow: Optional[int] = None\n result = [(flow, cost)]\n while flow < flow_limit:\n if not refine_dual():\n break\n f = flow_limit - flow\n v = t\n while prev[v] is not None:\n u, e = cast(Tuple[int, MCFGraph._Edge], prev[v])\n f = min(f, e.cap)\n v = u\n v = t\n while prev[v] is not None:\n u, e = cast(Tuple[int, MCFGraph._Edge], prev[v])\n e.cap -= f\n assert e.rev is not None\n e.rev.cap += f\n v = u\n c = -dual[s]\n flow += f\n cost += f * c\n if c == prev_cost_per_flow:\n result.pop()\n result.append((flow, cost))\n prev_cost_per_flow = c\n return result'), 'lib.misc': (False, 'from typing import List, Any, Callable, Sequence, Union, Tuple, TypeVar\nfrom numbers import Integral, Real\nimport sys\nfrom functools import reduce\nfrom itertools import accumulate\nfrom lib.data_structure import BinaryIndexedTree, DisjointSet\nimport bisect\nfrom lib.number_theory import modinv\nfrom collections import deque\n\nT = TypeVar(\'T\')\nM = TypeVar(\'M\')\nV = TypeVar(\'V\')\n\n\n\ndef general_bisect(ng: Integral, ok: Integral, judge: Callable[[Integral], bool]) -> Integral:\n """\n ???????????????????O(log L)??????\n\n :param ng: judge(ng)==False????\n :param ok: judge(ok)==True????\n :param judge: ??????????\n :return: judge(x)==True???????????\n """\n while abs(ng - ok) > 1:\n m = (ng + ok) // 2\n if judge(m):\n ok = m\n else:\n ng = m\n return ok\n\n\ndef general_bisect_float(ng: Real, ok: Real, judge: Callable[[Real], bool], tol: Real) -> Real:\n """\n ???????????????????O(log L)??????\n\n :param ng: judge(ng)==False????\n :param ok: judge(ok)==True????\n :param judge: ??????????\n :return: judge(x)==True???????????\n """\n while abs(ng - ok) > tol:\n m = (ng + ok) / 2\n if judge(m):\n ok = m\n else:\n ng = m\n return ok\n\n\ndef fibonacci_search(left: int, right: int, func: Union[Callable[[int], V], Sequence], inf: V = 2 ** 60) -> Tuple[\n V, int]:\n """\n ??????????????????????????????O(log L)??????\n ???(left, right)?????????\n\n :param left: ?????????????\n :param right: ?????????????\n :param func: ??????\n :param inf: func???\n :return: (func????, ????????func???)\n """\n try:\n func = func.__getitem__\n except AttributeError:\n pass\n f1, f2 = 1, 1\n while f1 + f2 < right - left:\n f1, f2 = f1 + f2, f1\n l = left\n m1 = func(l + f2)\n m2 = func(l + f1)\n while f1 > 2:\n f1, f2 = f2, f1 - f2\n if m1 > m2:\n l += f1\n m1 = m2\n m2 = func(l + f1) if l + f1 < right else inf\n else:\n m2 = m1\n m1 = func(l + f2)\n if m1 < m2:\n return m1, l + 1\n else:\n return m2, l + 2\n\n\ndef max2(x: V, y: V) -> V:\n return x if x > y else y\n\n\ndef min2(x: V, y: V) -> V:\n return x if x < y else y\n\n\nread = sys.stdin.buffer.read\nreadline = sys.stdin.buffer.readline\n\n\ndef rerooting(rooted_tree, merge, identity, finalize):\n """\n merge: (T,T) -> T, (T, merge)?????\n identity: ???\n finalize: (T, V, V) -> T\n\n ????????dp?????\n dp[u,v] = finalize(merge(dp[v,k] for k in adj[v] if k != u), u, v)\n ???(u,v)?? u->v\n """\n N = rooted_tree.n_vertices\n parent = rooted_tree.parent\n children = rooted_tree.children\n order = rooted_tree.dfs_order\n\n # from leaf to parent\n dp_down = [None] * N\n for v in reversed(order):\n dp_down[v] = finalize(reduce(merge,\n (dp_down[c] for c in children[v]),\n identity), parent[v], v)\n\n # from parent to leaf\n dp_up = [None] * N\n dp_up[0] = identity\n for v in order:\n if len(children[v]) == 0:\n continue\n temp = (dp_up[v],) + tuple(dp_down[u] for u in children[v]) + (identity,)\n left = accumulate(temp[:-2], merge)\n right = tuple(accumulate(reversed(temp[2:]), merge))\n for u, l, r in zip(children[v], left, reversed(right)):\n dp_up[u] = finalize(merge(l, r), u, v)\n\n res = [None] * N\n for v, l in enumerate(children):\n res[v] = reduce(merge,\n (dp_down[u] for u in children[v]),\n identity)\n res[v] = merge(res[v], dp_up[v])\n return res, dp_up, dp_down\n\n\ndef rerooting_fast(rooted_tree, merge, identity, finalize):\n """\n merge: (T,T) -> T, (T, merge)?????\n identity: ???\n finalize: (T, V, V) -> T\n\n ????????dp?????\n dp[u,v] = finalize(merge(dp[v,k] for k in adj[v] if k != u), u, v)\n ???(u,v)??\n dp[u,v]: v?????u?????????????????\n """\n dp1 = [identity] * rooted_tree.n_vertices\n dp2 = [identity] * rooted_tree.n_vertices\n\n for v in rooted_tree.post_order:\n t = identity\n for u in rooted_tree.children(v):\n dp2[u] = t\n t = merge(t, finalize(dp1[u], v, u))\n t = identity\n for u in reversed(rooted_tree.children(v)):\n dp2[u] = merge(t, dp2[u])\n t = merge(t, finalize(dp1[u], v, u))\n dp1[v] = t\n for v in rooted_tree.pre_order:\n p = rooted_tree.parent(v)\n if p >= 0:\n dp2[v] = finalize(merge(dp2[v], dp2[p]), v, p)\n dp1[v] = merge(dp1[v], dp2[v])\n return dp1\n\n\ndef longest_increasing_sequence(l, inf, strict=True):\n if not l:\n return 0\n dp = [inf] * len(l)\n if strict:\n for i, v in enumerate(l):\n dp[bisect.bisect_left(dp, v)] = v\n else:\n for i, v in enumerate(l):\n dp[bisect.bisect_right(dp, v)] = v\n\n m = next(n for n in reversed(range(len(l))) if dp[n] < inf) + 1\n return m\n\n\n\n\ndef check_bipartiteness(n_vertices, edges):\n ds = DisjointSet.empty(2 * n_vertices)\n\n for a, b in edges:\n ds.union(a, b + n_vertices)\n ds.union(b, a + n_vertices)\n\n next_color = 0\n color = [-1] * (2 * n_vertices)\n for v in range(n_vertices):\n ra = ds.find(v)\n rb = ds.find(v + n_vertices)\n if ra == rb:\n return None\n if color[ra] < 0:\n color[ra] = next_color\n color[rb] = next_color + 1\n next_color += 2\n color[v] = color[ra]\n color[v + n_vertices] = color[rb]\n return color[:n_vertices]\n\n\ndef small_range_duplicate(a: List[int]) -> Tuple[List[int], List[int]]:\n MASK = (1 << 32) - 1\n n = len(a)\n left = [i - 1 for i in range(n + 1)]\n right = [i + 1 for i in range(n + 1)]\n\n sorted_ind = sorted((~v << 32) | i for i, v in enumerate(a))\n t = 0\n vi = sorted_ind[t]\n i = vi & MASK\n v = ~(vi >> 32)\n while t < n:\n j = i\n l = left[i]\n pi = l\n pv = v\n while v == pv and left[i] == pi:\n pi = i\n t += 1\n if t >= n:\n break\n vi = sorted_ind[t]\n i = vi & MASK\n v = ~(vi >> 32)\n r = right[pi]\n right[l] = r\n while j <= pi:\n nj = right[j]\n left[j] = l\n right[j] = r\n j = nj\n left[r] = l\n\n return left, right\n\n\ndef small_range(a: List[int]) -> Tuple[List[int], List[int]]:\n N = len(a)\n MASK = (1 << 32) - 1\n left = [i - 1 for i in range(N + 1)]\n right = [i + 1 for i in range(N + 1)]\n sorted_ind = sorted((~v << 32) | i for i, v in enumerate(a))\n for v in sorted_ind:\n i = v & MASK\n left[right[-i]] = left[-i]\n right[left[-i]] = right[-i]\n\n return left, right\n\n\ndef popcnt32(n: int) -> int:\n n = n - ((n >> 1) & 0x55555555)\n n = (n & 0x33333333) + ((n >> 2) & 0x33333333)\n return ((((n + (n >> 4)) & 0x0f0f0f0f) * 0x01010101) >> 24) & 0xff\n\n\ndef popcnt64(n: int) -> int:\n n = n - ((n >> 1) & 0x5555555555555555)\n n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333)\n n = (n + (n >> 4)) & 0x0f0f0f0f0f0f0f0f\n return ((((n + (n >> 32)) & 0xffffffff) * 0x01010101) >> 24) & 0xff\n\n\ndef popcnt(n: int) -> int:\n if n < 1 << 32:\n return popcnt32(n)\n elif n < 1 << 64:\n return popcnt64(n)\n else:\n return sum(c == \'1\' for c in bin(n))\n\n\ndef reverse_bits32(x: int):\n x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1)\n x = ((x & 0x33333333) << 2) | ((x & 0xCCCCCCCC) >> 2)\n x = ((x & 0x0F0F0F0F) << 4) | ((x & 0xF0F0F0F0) >> 4)\n x = ((x & 0x00FF00FF) << 8) | ((x & 0xFF00FF00) >> 8)\n return ((x & 0x0000FFFF) << 16) | ((x & 0xFFFF0000) >> 16)\n\n\ndef count_inversions(l: List[Any]) -> int:\n """\n ?????????in-place????????\n\n :param l: ???\n :return: ???\n """\n bit = BinaryIndexedTree(len(l))\n res = 0\n for i, v in enumerate(l):\n bit[v] += 1\n res += bit[v + 1:]\n return res\n\n\ndef construct_xor_basis(iterable):\n """\n iterable??xor????????\n\n :param iterable: ?????????????\n :return: ?????int????\n """\n basis = []\n for e in iterable:\n for b in basis:\n e = min2(e, e ^ b)\n if e > 0:\n basis.append(e)\n return basis\n\n\ndef check_xor_span(basis, x):\n """\n x?basis???F2???????????????????\n basis????????????????????????\n\n :param basis: ??\n :param x: ?????\n :return: 0???????????????????????????????????\n """\n for b in basis:\n x = min2(x, x ^ b)\n return x\n\n\ndef get_rolling_hash(mods, bases):\n ib = [modinv(b, m) for b, m in zip(bases, mods)]\n k = len(mods)\n\n class RollingHash:\n """\n RollingHash object represents a hash of a sequence.\n O(1) to append/remove element from both front/end.\n\n """\n def __init__(self, hash, pb, l):\n self.hash = hash\n self.pb = pb\n self.l = l\n\n @classmethod\n def empty(cls):\n return cls([0]*k, [1]*k, 0)\n\n def _append_d(self, v):\n v += 1\n for i in range(k):\n self.hash[i] += v * self.pb[i]\n self.hash[i] %= mods[i]\n self.pb[i] = (self.pb[i]*bases[i]) % mods[i]\n self.l += 1\n\n def _appendleft_d(self, v):\n v += 1\n for i in range(k):\n self.hash[i] *= bases[i]\n self.hash[i] += v\n self.hash[i] %= mods[i]\n self.pb[i] = (self.pb[i]*bases[i]) % mods[i]\n self.l += 1\n\n def _pop_d(self, v):\n v += 1\n for i in range(k):\n self.pb[i] = (self.pb[i]*ib[i]) % mods[i]\n self.hash[i] -= v * self.pb[i]\n self.hash[i] %= mods[i]\n self.l -= 1\n\n def _popleft_d(self, v):\n v += 1\n for i in range(k):\n self.pb[i] = (self.pb[i]*ib[i]) % mods[i]\n self.hash[i] -= v\n self.hash[i] *= ib[i]\n self.hash[i] %= mods[i]\n self.l -= 1\n\n def append(self, v):\n h = self.copy()\n h._append_d(v)\n return h\n\n def appendleft(self, v):\n h = self.copy()\n h._appendleft_d(v)\n return h\n\n def pop(self, v):\n h = self.copy()\n h._pop_d(v)\n return h\n\n def popleft(self, v):\n h = self.copy()\n h._popleft_d(v)\n return h\n\n def __hash__(self):\n return hash(tuple(self.hash))\n\n def copy(self):\n return RollingHash(self.hash[:], self.pb[:], self.l)\n __copy__ = copy\n\n return RollingHash\n\n\ndef sliding_max(l, width):\n res = [0]*(len(l)-width+1)\n q = deque(maxlen=width+1)\n\n for i, v in enumerate(l):\n while q and l[q[0]] <= v:\n q.popleft()\n q.appendleft(i)\n while q[-1]+width <= i:\n q.pop()\n res[i-width+1] = l[q[-1]]\n return res\n\n'), 'lib.modint': (False, "from importlib.util import find_spec, module_from_spec\n\nmodints = {}\n\n\ndef get_modint(mod):\n try:\n return modints[mod]\n except KeyError:\n spec = find_spec('lib._modint')\n module = module_from_spec(spec)\n module.__dict__['MOD'] = mod\n spec.loader.exec_module(module)\n modints[mod] = module.ModInt\n return modints[mod]"), 'lib.number_theory': (False, 'from collections import Counter, defaultdict\nfrom math import sqrt, ceil, gcd\nfrom itertools import count\nfrom typing import *\n\n\ndef sign(x):\n return int(x > 0) - int(x < 0)\n\n\ndef egcd(a: int, b: int) -> Tuple[int, int, int]:\n """\n ?????????\n\n :param a: ??\n :param b: ??\n :return: (x, y, gcd(a,b)). x, y?ax+by=gcd(a,b)????\n """\n s, ps, r, pr = 0, 1, b, a\n while r != 0:\n q = pr // r\n pr, r = r, pr - q * r\n ps, s = s, ps - q * s\n t = (pr - ps * a) // b\n if pr > 0:\n return ps, t, pr\n return -ps, -t, -pr\n\n\ndef modinv(x: int, mod: int) -> int:\n """\n Z/(mod Z)???x???\n\n :param x: ??\n :param mod: ??\n :return: x * y % mod = 1????y\n """\n s, ps, r, pr = 0, 1, mod, x\n while r != 0:\n pr, (q, r) = r, divmod(pr, r)\n ps, s = s, ps - q * s\n if pr == 1:\n return ps if ps >= 0 else ps + mod\n raise ValueError("base is not invertible for the given modulus")\n\n\ndef modpow(x, k, mod):\n """\n Z/(mod Z)???x?k?\n\n :param x: ??\n :param k: ??\n :param mod: ??\n :return: x ** k % mod\n """\n if k < 0:\n x = modinv(x, mod)\n k = -k\n r = 1\n while k != 0:\n if k & 1:\n r = (r * x) % mod\n x = (x * x) % mod\n k >>= 1\n return r\n\n\n# ?????\ndef prime_factors(n):\n """\n n??????????\n\n :param n: ???\n :return: n????????????????generator\n """\n i = 2\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n //= i\n yield i\n if n > 1:\n yield n\n\n\ndef int_product(iterable):\n x = 1\n for y in iterable:\n x *= y\n return x\n\n\n# ?????O(sqrt(n))????\ndef divisors(n):\n for i in range(1, ceil(sqrt(n)) + 1):\n j, r = divmod(n, i)\n if not r:\n yield i\n if i != j:\n yield j\n\n\n# ?????\ndef generate_primes():\n d = defaultdict(list)\n\n for q in count(2):\n if q in d:\n for p in d[q]:\n d[p + q].append(p)\n del d[q]\n else:\n yield q\n d[q * q].append(q)\n\n\ndef totient_factors(n):\n def it():\n prev = -1\n for p in prime_factors(n):\n if p == prev:\n yield p\n else:\n prev = p\n for q in prime_factors(p - 1):\n yield q\n return it()\n\n\ndef primitive_root(mod, phi_factors=None):\n if phi_factors is None:\n phi_factors = tuple(totient_factors(mod))\n phi = int_product(phi_factors)\n primes = set(phi_factors)\n for i in range(2, mod):\n for p in primes:\n if modpow(i, (phi // p), mod) == 1:\n break\n else:\n return i\n else:\n raise ValueError(f\'There is no primitive root for modulo {mod}\')\n\n\ndef lcm(nums: Iterable[int]) -> int:\n m = 1\n for n in nums:\n m *= n // gcd(m, n)\n return m\n\n\ndef chinese_remainder_theorem(reminders: List[int], mods: List[int], mods_lcm: int=-1) -> Tuple[int, int]:\n """\n returns x and lcm(reminders) s.t.\n all(x%m == r for r,m in zip(reminders,mods))\n """\n s = 0\n if mods_lcm < 0:\n mods_lcm = lcm(mods)\n for m, r in zip(mods, reminders):\n p = mods_lcm // m\n s += r * p * modinv(p, m)\n s %= mods_lcm\n return s, mods_lcm\n\n\ndef factorials_with_inv(k, mod):\n """\n 0! ... k! ?????mod????????\n """\n fac = [1] * (k + 1)\n inv = [1] * (k + 1)\n t = 1\n for i in range(1, k + 1):\n t = (t * i) % mod\n fac[i] = t\n t = modinv(t, mod)\n for i in reversed(range(1, k + 1)):\n inv[i] = t\n t = (t * i) % mod\n return fac, inv\n\n\ndef extended_lucas_theorem(mod):\n """\n Returns a function (n,m) -> C(n,m)%mod\n """\n factors = tuple((p, q, p ** q) for p, q in Counter(prime_factors(mod)).items())\n facs = [[0] * k for p, q, k in factors]\n invs = [[0] * k for p, q, k in factors]\n for (p, q, k), fac, inv in zip(factors, facs, invs):\n t = 1\n for n in range(k):\n if n % p != 0:\n t *= n\n t %= k\n fac[n] = t\n t = modinv(t, k)\n for n in reversed(range(k)):\n inv[n] = t\n if n % p != 0:\n t *= n\n t %= k\n\n def helper(n, m):\n l = n - m\n if l < 0:\n return 0\n\n def reminders():\n for (p, q, k), fac, inv in zip(factors, facs, invs):\n a, b, c, e0, eq, i, r = n, m, l, 0, -2, 1, 1\n while a > 0:\n r *= fac[a % k] * inv[b % k] * inv[c % k]\n r %= k\n a, b, c = a // p, b // p, c // p\n if i == q:\n eq = e0\n e0 += a - b - c\n i += 1\n if eq >= 0:\n eq += e0\n if e0 >= q:\n r = 0\n else:\n r *= p ** e0\n r %= k\n if not (p == 2 and q >= 3) and (eq % 2 == 1):\n r = -r\n yield r\n\n return chinese_remainder_theorem(reminders(), (m for _, _, m in factors), mod)[0]\n\n return helper\n\n\ndef lucas_theorem(m, n, mod, comb):\n cnt = 1\n while n > 0:\n m, mr = divmod(m, mod)\n n, nr = divmod(n, mod)\n if mr < nr:\n return 0\n cnt *= comb(mr, nr)\n cnt %= mod\n return cnt\n\n\n# C(n,m) is even iff (~n&m)\n\ndef floor_linear_sum(n, m, a, b):\n """\n returns sum((a*i+b)//m for i in range(n))\n """\n if b < 0:\n t = (-b - 1) // m + 1\n b += m * t\n res = -t * n\n else:\n res = 0\n while True:\n if a >= m:\n res += (n - 1) * n * (a // m) // 2\n a %= m\n if b >= m:\n res += n * (b // m)\n b %= m\n\n y_max = (a * n + b) // m\n if y_max == 0:\n return res\n nx_max = b - y_max * m\n res += (n + nx_max // a) * y_max\n n, m, a, b = y_max, a, m, nx_max % a\n\ndef get_sieve(n):\n sieve = [0]*(n+1)\n for i in range(2, len(sieve)):\n if sieve[i] > 0:\n continue\n sieve[i] = i\n for j in range(i*2, len(sieve), i):\n if sieve[j] == 0:\n sieve[j] = i\n return sieve\n\n\ndef divisors_from_sieve(n, sieve):\n res = [1]\n while n > 1:\n k = sieve[n]\n n //= k\n l = len(res)\n t = k\n res.extend(res[i]*t for i in range(l))\n while n > 1 and sieve[n] == k:\n t *= k\n res.extend(res[i]*t for i in range(l))\n n //= k\n return res\n\n\ndef factorize_from_sieve(n, sieve):\n while n > 1:\n yield sieve[n]\n n //= sieve[n]\n\n\ndef discrete_log(x: int, y: int, m: int) -> int:\n """\n x**k == y mod m ?????????k????\n\n :param x: ???????\n :param y: ??????????\n :param m: mod\n :return: ?????\n """\n\n x = int(x)\n y = int(y)\n m = int(m)\n if y >= m or y < 0:\n return -1\n if x == 0:\n if m == 1:\n return 0\n if y == 1:\n return 0\n if y == 0:\n return 1\n return -1\n p = 3\n tmp = x - 1\n cnt = 0\n primes = []\n counts = []\n ps = 0\n while tmp & 1:\n tmp >>= 1\n cnt += 1\n if cnt:\n primes.append(2)\n counts.append(cnt)\n ps += 1\n tmp += 1\n while tmp != 1:\n cnt = 0\n while tmp % p == 0:\n tmp //= p\n cnt += 1\n if cnt:\n primes.append(p)\n counts.append(cnt)\n ps += 1\n p += 2\n if tmp != 1 and p * p > x:\n primes.append(tmp)\n counts.append(1)\n ps += 1\n break\n tail = 0\n mp = m\n for i in range(ps):\n f = 0\n while mp % primes[i] == 0:\n mp //= primes[i]\n f += 1\n if tail < (f + counts[i] - 1) // counts[i]:\n tail = (f + counts[i] - 1) // counts[i]\n z = 1\n for i in range(tail):\n if z == y:\n return i\n z = z * x % m\n if y % gcd(z, m):\n return -1\n p = 3\n u = mp\n tmp = mp - 1\n if tmp & 1:\n u >>= 1\n while tmp & 1:\n tmp >>= 1\n tmp += 1\n while tmp != 1:\n if tmp % p == 0:\n u //= p\n u *= p - 1\n while tmp % p == 0:\n tmp //= p\n p += 2\n if tmp != 1 and p * p > mp:\n u //= tmp\n u *= tmp - 1\n break\n p = 1\n loop = u\n while p * p <= u:\n if u % p == 0:\n if z * modpow(x, p, m) % m == z:\n loop = p\n break\n ip = u // p\n if z * modpow(x, ip, m) % m == z:\n loop = ip\n p += 1\n l, r = 0, loop+1\n sq = (loop+1) >> 1\n while r - l > 1:\n if sq * sq <= loop:\n l = sq\n else:\n r = sq\n sq = (l + r) >> 1\n if sq * sq < loop:\n sq += 1\n b = modpow(modpow(x, loop-1, m), sq, m)\n d = {}\n f = z\n for i in range(sq):\n d[f] = i\n f = f * x % m\n g = y\n for i in range(sq):\n if g in d:\n return i*sq+d[g]+tail\n g = g * b % m\n return -1\n\n'), 'lib.online_sorted_list': (False, 'import sys\nimport traceback\n\nfrom bisect import bisect_left, bisect_right, insort\nfrom itertools import chain, repeat, starmap\nfrom math import log\nfrom operator import add, eq, ne, gt, ge, lt, le, iadd\nfrom textwrap import dedent\n\ntry:\n from collections.abc import Sequence, MutableSequence\nexcept ImportError:\n from collections import Sequence, MutableSequence\n\nfrom functools import wraps\nfrom sys import hexversion\n\nif hexversion < 0x03000000:\n try:\n from thread import get_ident\n except ImportError:\n from dummy_thread import get_ident\nelse:\n from functools import reduce\n\n try:\n from _thread import get_ident\n except ImportError:\n from _dummy_thread import get_ident\n\n\ndef recursive_repr(fillvalue=\'...\'):\n "Decorator to make a repr function return fillvalue for a recursive call."\n\n # pylint: disable=missing-docstring\n # Copied from reprlib in Python 3\n # https://hg.python.org/cpython/file/3.6/Lib/reprlib.py\n\n def decorating_function(user_function):\n repr_running = set()\n\n @wraps(user_function)\n def wrapper(self):\n key = id(self), get_ident()\n if key in repr_running:\n return fillvalue\n repr_running.add(key)\n try:\n result = user_function(self)\n finally:\n repr_running.discard(key)\n return result\n\n return wrapper\n\n return decorating_function\n\n\nclass OnlineSortedList(MutableSequence):\n """Sorted list is a sorted mutable sequence.\n\n Sorted list values are maintained in sorted order.\n\n Sorted list values must be comparable. The total ordering of values must\n not change while they are stored in the sorted list.\n\n Methods for adding values:\n\n * :func:`SortedList.add`\n * :func:`SortedList.update`\n * :func:`SortedList.__add__`\n * :func:`SortedList.__iadd__`\n * :func:`SortedList.__mul__`\n * :func:`SortedList.__imul__`\n\n Methods for removing values:\n\n * :func:`SortedList.clear`\n * :func:`SortedList.discard`\n * :func:`SortedList.remove`\n * :func:`SortedList.pop`\n * :func:`SortedList.__delitem__`\n\n Methods for looking up values:\n\n * :func:`SortedList.bisect_left`\n * :func:`SortedList.bisect_right`\n * :func:`SortedList.count`\n * :func:`SortedList.index`\n * :func:`SortedList.__contains__`\n * :func:`SortedList.__getitem__`\n\n Methods for iterating values:\n\n * :func:`SortedList.irange`\n * :func:`SortedList.islice`\n * :func:`SortedList.__iter__`\n * :func:`SortedList.__reversed__`\n\n Methods for miscellany:\n\n * :func:`SortedList.copy`\n * :func:`SortedList.__len__`\n * :func:`SortedList.__repr__`\n * :func:`SortedList._check`\n * :func:`SortedList._reset`\n\n Sorted lists use lexicographical ordering semantics when compared to other\n sequences.\n\n Some methods of mutable sequences are not supported and will raise\n not-implemented error.\n\n """\n DEFAULT_LOAD_FACTOR = 1000\n\n def __init__(self, iterable=None, key=None):\n """Initialize sorted list instance.\n\n Optional `iterable` argument provides an initial iterable of values to\n initialize the sorted list.\n\n Runtime complexity: `O(n*log(n))`\n\n >>> sl = SortedList()\n >>> sl\n SortedList([])\n >>> sl = SortedList([3, 1, 2, 5, 4])\n >>> sl\n SortedList([1, 2, 3, 4, 5])\n\n :param iterable: initial values (optional)\n\n """\n assert key is None\n self._len = 0\n self._load = self.DEFAULT_LOAD_FACTOR\n self._lists = []\n self._maxes = []\n self._index = []\n self._offset = 0\n\n if iterable is not None:\n self._update(iterable)\n\n def __new__(cls, iterable=None, key=None):\n """Create new sorted list or sorted-key list instance.\n\n Optional `key`-function argument will return an instance of subtype\n :class:`SortedKeyList`.\n\n >>> sl = SortedList()\n >>> isinstance(sl, SortedList)\n True\n >>> sl = SortedList(key=lambda x: -x)\n >>> isinstance(sl, SortedList)\n True\n >>> isinstance(sl, SortedKeyList)\n True\n\n :param iterable: initial values (optional)\n :param key: function used to extract comparison key (optional)\n :return: sorted list or sorted-key list instance\n\n """\n # pylint: disable=unused-argument\n if key is None:\n return object.__new__(cls)\n else:\n if cls is SortedList:\n return object.__new__(SortedKeyList)\n else:\n raise TypeError(\'inherit SortedKeyList for key argument\')\n\n @property\n def key(self): # pylint: disable=useless-return\n """Function used to extract comparison key from values.\n\n Sorted list compares values directly so the key function is none.\n\n """\n return None\n\n def _reset(self, load):\n """Reset sorted list load factor.\n\n The `load` specifies the load-factor of the list. The default load\n factor of 1000 works well for lists from tens to tens-of-millions of\n values. Good practice is to use a value that is the cube root of the\n list size. With billions of elements, the best load factor depends on\n your usage. It\'s best to leave the load factor at the default until you\n start benchmarking.\n\n See :doc:`implementation` and :doc:`performance-scale` for more\n information.\n\n Runtime complexity: `O(n)`\n\n :param int load: load-factor for sorted list sublists\n\n """\n values = reduce(iadd, self._lists, [])\n self._clear()\n self._load = load\n self._update(values)\n\n def clear(self):\n """Remove all values from sorted list.\n\n Runtime complexity: `O(n)`\n\n """\n self._len = 0\n del self._lists[:]\n del self._maxes[:]\n del self._index[:]\n self._offset = 0\n\n _clear = clear\n\n def add(self, value):\n """Add `value` to sorted list.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList()\n >>> sl.add(3)\n >>> sl.add(1)\n >>> sl.add(2)\n >>> sl\n SortedList([1, 2, 3])\n\n :param value: value to add to sorted list\n\n """\n _lists = self._lists\n _maxes = self._maxes\n\n if _maxes:\n pos = bisect_right(_maxes, value)\n\n if pos == len(_maxes):\n pos -= 1\n _lists[pos].append(value)\n _maxes[pos] = value\n else:\n insort(_lists[pos], value)\n\n self._expand(pos)\n else:\n _lists.append([value])\n _maxes.append(value)\n\n self._len += 1\n\n def _expand(self, pos):\n """Split sublists with length greater than double the load-factor.\n\n Updates the index when the sublist length is less than double the load\n level. This requires incrementing the nodes in a traversal from the\n leaf node to the root. For an example traversal see\n ``SortedList._loc``.\n\n """\n _load = self._load\n _lists = self._lists\n _index = self._index\n\n if len(_lists[pos]) > (_load << 1):\n _maxes = self._maxes\n\n _lists_pos = _lists[pos]\n half = _lists_pos[_load:]\n del _lists_pos[_load:]\n _maxes[pos] = _lists_pos[-1]\n\n _lists.insert(pos + 1, half)\n _maxes.insert(pos + 1, half[-1])\n\n del _index[:]\n else:\n if _index:\n child = self._offset + pos\n while child:\n _index[child] += 1\n child = (child - 1) >> 1\n _index[0] += 1\n\n def update(self, iterable):\n """Update sorted list by adding all values from `iterable`.\n\n Runtime complexity: `O(k*log(n))` -- approximate.\n\n >>> sl = SortedList()\n >>> sl.update([3, 1, 2])\n >>> sl\n SortedList([1, 2, 3])\n\n :param iterable: iterable of values to add\n\n """\n _lists = self._lists\n _maxes = self._maxes\n values = sorted(iterable)\n\n if _maxes:\n if len(values) * 4 >= self._len:\n _lists.append(values)\n values = reduce(iadd, _lists, [])\n values.sort()\n self._clear()\n else:\n _add = self.add\n for val in values:\n _add(val)\n return\n\n _load = self._load\n _lists.extend(values[pos:(pos + _load)]\n for pos in range(0, len(values), _load))\n _maxes.extend(sublist[-1] for sublist in _lists)\n self._len = len(values)\n del self._index[:]\n\n _update = update\n\n def __contains__(self, value):\n """Return true if `value` is an element of the sorted list.\n\n ``sl.__contains__(value)`` <==> ``value in sl``\n\n Runtime complexity: `O(log(n))`\n\n >>> sl = SortedList([1, 2, 3, 4, 5])\n >>> 3 in sl\n True\n\n :param value: search for value in sorted list\n :return: true if `value` in sorted list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return False\n\n pos = bisect_left(_maxes, value)\n\n if pos == len(_maxes):\n return False\n\n _lists = self._lists\n idx = bisect_left(_lists[pos], value)\n\n return _lists[pos][idx] == value\n\n def discard(self, value):\n """Remove `value` from sorted list if it is a member.\n\n If `value` is not a member, do nothing.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList([1, 2, 3, 4, 5])\n >>> sl.discard(5)\n >>> sl.discard(0)\n >>> sl == [1, 2, 3, 4]\n True\n\n :param value: `value` to discard from sorted list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return\n\n pos = bisect_left(_maxes, value)\n\n if pos == len(_maxes):\n return\n\n _lists = self._lists\n idx = bisect_left(_lists[pos], value)\n\n if _lists[pos][idx] == value:\n self._delete(pos, idx)\n\n def remove(self, value):\n """Remove `value` from sorted list; `value` must be a member.\n\n If `value` is not a member, raise ValueError.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList([1, 2, 3, 4, 5])\n >>> sl.remove(5)\n >>> sl == [1, 2, 3, 4]\n True\n >>> sl.remove(0)\n Traceback (most recent call last):\n ...\n ValueError: 0 not in list\n\n :param value: `value` to remove from sorted list\n :raises ValueError: if `value` is not in sorted list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n raise ValueError(\'{0!r} not in list\'.format(value))\n\n pos = bisect_left(_maxes, value)\n\n if pos == len(_maxes):\n raise ValueError(\'{0!r} not in list\'.format(value))\n\n _lists = self._lists\n idx = bisect_left(_lists[pos], value)\n\n if _lists[pos][idx] == value:\n self._delete(pos, idx)\n else:\n raise ValueError(\'{0!r} not in list\'.format(value))\n\n def _delete(self, pos, idx):\n """Delete value at the given `(pos, idx)`.\n\n Combines lists that are less than half the load level.\n\n Updates the index when the sublist length is more than half the load\n level. This requires decrementing the nodes in a traversal from the\n leaf node to the root. For an example traversal see\n ``SortedList._loc``.\n\n :param int pos: lists index\n :param int idx: sublist index\n\n """\n _lists = self._lists\n _maxes = self._maxes\n _index = self._index\n\n _lists_pos = _lists[pos]\n\n del _lists_pos[idx]\n self._len -= 1\n\n len_lists_pos = len(_lists_pos)\n\n if len_lists_pos > (self._load >> 1):\n _maxes[pos] = _lists_pos[-1]\n\n if _index:\n child = self._offset + pos\n while child > 0:\n _index[child] -= 1\n child = (child - 1) >> 1\n _index[0] -= 1\n elif len(_lists) > 1:\n if not pos:\n pos += 1\n\n prev = pos - 1\n _lists[prev].extend(_lists[pos])\n _maxes[prev] = _lists[prev][-1]\n\n del _lists[pos]\n del _maxes[pos]\n del _index[:]\n\n self._expand(prev)\n elif len_lists_pos:\n _maxes[pos] = _lists_pos[-1]\n else:\n del _lists[pos]\n del _maxes[pos]\n del _index[:]\n\n def _loc(self, pos, idx):\n """Convert an index pair (lists index, sublist index) into a single\n index number that corresponds to the position of the value in the\n sorted list.\n\n Many queries require the index be built. Details of the index are\n described in ``SortedList._build_index``.\n\n Indexing requires traversing the tree from a leaf node to the root. The\n parent of each node is easily computable at ``(pos - 1) // 2``.\n\n Left-child nodes are always at odd indices and right-child nodes are\n always at even indices.\n\n When traversing up from a right-child node, increment the total by the\n left-child node.\n\n The final index is the sum from traversal and the index in the sublist.\n\n For example, using the index from ``SortedList._build_index``::\n\n _index = 14 5 9 3 2 4 5\n _offset = 3\n\n Tree::\n\n 14\n 5 9\n 3 2 4 5\n\n Converting an index pair (2, 3) into a single index involves iterating\n like so:\n\n 1. Starting at the leaf node: offset + alpha = 3 + 2 = 5. We identify\n the node as a left-child node. At such nodes, we simply traverse to\n the parent.\n\n 2. At node 9, position 2, we recognize the node as a right-child node\n and accumulate the left-child in our total. Total is now 5 and we\n traverse to the parent at position 0.\n\n 3. Iteration ends at the root.\n\n The index is then the sum of the total and sublist index: 5 + 3 = 8.\n\n :param int pos: lists index\n :param int idx: sublist index\n :return: index in sorted list\n\n """\n if not pos:\n return idx\n\n _index = self._index\n\n if not _index:\n self._build_index()\n\n total = 0\n\n # Increment pos to point in the index to len(self._lists[pos]).\n\n pos += self._offset\n\n # Iterate until reaching the root of the index tree at pos = 0.\n\n while pos:\n\n # Right-child nodes are at odd indices. At such indices\n # account the total below the left child node.\n\n if not pos & 1:\n total += _index[pos - 1]\n\n # Advance pos to the parent node.\n\n pos = (pos - 1) >> 1\n\n return total + idx\n\n def _pos(self, idx):\n """Convert an index into an index pair (lists index, sublist index)\n that can be used to access the corresponding lists position.\n\n Many queries require the index be built. Details of the index are\n described in ``SortedList._build_index``.\n\n Indexing requires traversing the tree to a leaf node. Each node has two\n children which are easily computable. Given an index, pos, the\n left-child is at ``pos * 2 + 1`` and the right-child is at ``pos * 2 +\n 2``.\n\n When the index is less than the left-child, traversal moves to the\n left sub-tree. Otherwise, the index is decremented by the left-child\n and traversal moves to the right sub-tree.\n\n At a child node, the indexing pair is computed from the relative\n position of the child node as compared with the offset and the remaining\n index.\n\n For example, using the index from ``SortedList._build_index``::\n\n _index = 14 5 9 3 2 4 5\n _offset = 3\n\n Tree::\n\n 14\n 5 9\n 3 2 4 5\n\n Indexing position 8 involves iterating like so:\n\n 1. Starting at the root, position 0, 8 is compared with the left-child\n node (5) which it is greater than. When greater the index is\n decremented and the position is updated to the right child node.\n\n 2. At node 9 with index 3, we again compare the index to the left-child\n node with value 4. Because the index is the less than the left-child\n node, we simply traverse to the left.\n\n 3. At node 4 with index 3, we recognize that we are at a leaf node and\n stop iterating.\n\n 4. To compute the sublist index, we subtract the offset from the index\n of the leaf node: 5 - 3 = 2. To compute the index in the sublist, we\n simply use the index remaining from iteration. In this case, 3.\n\n The final index pair from our example is (2, 3) which corresponds to\n index 8 in the sorted list.\n\n :param int idx: index in sorted list\n :return: (lists index, sublist index) pair\n\n """\n if idx < 0:\n last_len = len(self._lists[-1])\n\n if (-idx) <= last_len:\n return len(self._lists) - 1, last_len + idx\n\n idx += self._len\n\n if idx < 0:\n raise IndexError(\'list index out of range\')\n elif idx >= self._len:\n raise IndexError(\'list index out of range\')\n\n if idx < len(self._lists[0]):\n return 0, idx\n\n _index = self._index\n\n if not _index:\n self._build_index()\n\n pos = 0\n child = 1\n len_index = len(_index)\n\n while child < len_index:\n index_child = _index[child]\n\n if idx < index_child:\n pos = child\n else:\n idx -= index_child\n pos = child + 1\n\n child = (pos << 1) + 1\n\n return (pos - self._offset, idx)\n\n def _build_index(self):\n """Build a positional index for indexing the sorted list.\n\n Indexes are represented as binary trees in a dense array notation\n similar to a binary heap.\n\n For example, given a lists representation storing integers::\n\n 0: [1, 2, 3]\n 1: [4, 5]\n 2: [6, 7, 8, 9]\n 3: [10, 11, 12, 13, 14]\n\n The first transformation maps the sub-lists by their length. The\n first row of the index is the length of the sub-lists::\n\n 0: [3, 2, 4, 5]\n\n Each row after that is the sum of consecutive pairs of the previous\n row::\n\n 1: [5, 9]\n 2: [14]\n\n Finally, the index is built by concatenating these lists together::\n\n _index = [14, 5, 9, 3, 2, 4, 5]\n\n An offset storing the start of the first row is also stored::\n\n _offset = 3\n\n When built, the index can be used for efficient indexing into the list.\n See the comment and notes on ``SortedList._pos`` for details.\n\n """\n row0 = list(map(len, self._lists))\n\n if len(row0) == 1:\n self._index[:] = row0\n self._offset = 0\n return\n\n head = iter(row0)\n tail = iter(head)\n row1 = list(starmap(add, zip(head, tail)))\n\n if len(row0) & 1:\n row1.append(row0[-1])\n\n if len(row1) == 1:\n self._index[:] = row1 + row0\n self._offset = 1\n return\n\n size = 2 ** (int(log(len(row1) - 1, 2)) + 1)\n row1.extend(repeat(0, size - len(row1)))\n tree = [row0, row1]\n\n while len(tree[-1]) > 1:\n head = iter(tree[-1])\n tail = iter(head)\n row = list(starmap(add, zip(head, tail)))\n tree.append(row)\n\n reduce(iadd, reversed(tree), self._index)\n self._offset = size * 2 - 1\n\n def __delitem__(self, index):\n """Remove value at `index` from sorted list.\n\n ``sl.__delitem__(index)`` <==> ``del sl[index]``\n\n Supports slicing.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList(\'abcde\')\n >>> del sl[2]\n >>> sl\n SortedList([\'a\', \'b\', \'d\', \'e\'])\n >>> del sl[:2]\n >>> sl\n SortedList([\'d\', \'e\'])\n\n :param index: integer or slice for indexing\n :raises IndexError: if index out of range\n\n """\n if isinstance(index, slice):\n start, stop, step = index.indices(self._len)\n\n if step == 1 and start < stop:\n if start == 0 and stop == self._len:\n return self._clear()\n elif self._len <= 8 * (stop - start):\n values = self._getitem(slice(None, start))\n if stop < self._len:\n values += self._getitem(slice(stop, None))\n self._clear()\n return self._update(values)\n\n indices = range(start, stop, step)\n\n # Delete items from greatest index to least so\n # that the indices remain valid throughout iteration.\n\n if step > 0:\n indices = reversed(indices)\n\n _pos, _delete = self._pos, self._delete\n\n for index in indices:\n pos, idx = _pos(index)\n _delete(pos, idx)\n else:\n pos, idx = self._pos(index)\n self._delete(pos, idx)\n\n def __getitem__(self, index):\n """Lookup value at `index` in sorted list.\n\n ``sl.__getitem__(index)`` <==> ``sl[index]``\n\n Supports slicing.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList(\'abcde\')\n >>> sl[1]\n \'b\'\n >>> sl[-1]\n \'e\'\n >>> sl[2:5]\n [\'c\', \'d\', \'e\']\n\n :param index: integer or slice for indexing\n :return: value or list of values\n :raises IndexError: if index out of range\n\n """\n _lists = self._lists\n\n if isinstance(index, slice):\n start, stop, step = index.indices(self._len)\n\n if step == 1 and start < stop:\n # Whole slice optimization: start to stop slices the whole\n # sorted list.\n\n if start == 0 and stop == self._len:\n return reduce(iadd, self._lists, [])\n\n start_pos, start_idx = self._pos(start)\n start_list = _lists[start_pos]\n stop_idx = start_idx + stop - start\n\n # Small slice optimization: start index and stop index are\n # within the start list.\n\n if len(start_list) >= stop_idx:\n return start_list[start_idx:stop_idx]\n\n if stop == self._len:\n stop_pos = len(_lists) - 1\n stop_idx = len(_lists[stop_pos])\n else:\n stop_pos, stop_idx = self._pos(stop)\n\n prefix = _lists[start_pos][start_idx:]\n middle = _lists[(start_pos + 1):stop_pos]\n result = reduce(iadd, middle, prefix)\n result += _lists[stop_pos][:stop_idx]\n\n return result\n\n if step == -1 and start > stop:\n result = self._getitem(slice(stop + 1, start + 1))\n result.reverse()\n return result\n\n # Return a list because a negative step could\n # reverse the order of the items and this could\n # be the desired behavior.\n\n indices = range(start, stop, step)\n return list(self._getitem(index) for index in indices)\n else:\n if self._len:\n if index == 0:\n return _lists[0][0]\n elif index == -1:\n return _lists[-1][-1]\n else:\n raise IndexError(\'list index out of range\')\n\n if 0 <= index < len(_lists[0]):\n return _lists[0][index]\n\n len_last = len(_lists[-1])\n\n if -len_last < index < 0:\n return _lists[-1][len_last + index]\n\n pos, idx = self._pos(index)\n return _lists[pos][idx]\n\n _getitem = __getitem__\n\n def __setitem__(self, index, value):\n """Raise not-implemented error.\n\n ``sl.__setitem__(index, value)`` <==> ``sl[index] = value``\n\n :raises NotImplementedError: use ``del sl[index]`` and\n ``sl.add(value)`` instead\n\n """\n message = \'use ``del sl[index]`` and ``sl.add(value)`` instead\'\n raise NotImplementedError(message)\n\n def __iter__(self):\n """Return an iterator over the sorted list.\n\n ``sl.__iter__()`` <==> ``iter(sl)``\n\n Iterating the sorted list while adding or deleting values may raise a\n :exc:`RuntimeError` or fail to iterate over all values.\n\n """\n return chain.from_iterable(self._lists)\n\n def __reversed__(self):\n """Return a reverse iterator over the sorted list.\n\n ``sl.__reversed__()`` <==> ``reversed(sl)``\n\n Iterating the sorted list while adding or deleting values may raise a\n :exc:`RuntimeError` or fail to iterate over all values.\n\n """\n return chain.from_iterable(map(reversed, reversed(self._lists)))\n\n def reverse(self):\n """Raise not-implemented error.\n\n Sorted list maintains values in ascending sort order. Values may not be\n reversed in-place.\n\n Use ``reversed(sl)`` for an iterator over values in descending sort\n order.\n\n Implemented to override `MutableSequence.reverse` which provides an\n erroneous default implementation.\n\n :raises NotImplementedError: use ``reversed(sl)`` instead\n\n """\n raise NotImplementedError(\'use ``reversed(sl)`` instead\')\n\n def islice(self, start=None, stop=None, reverse=False):\n """Return an iterator that slices sorted list from `start` to `stop`.\n\n The `start` and `stop` index are treated inclusive and exclusive,\n respectively.\n\n Both `start` and `stop` default to `None` which is automatically\n inclusive of the beginning and end of the sorted list.\n\n When `reverse` is `True` the values are yielded from the iterator in\n reverse order; `reverse` defaults to `False`.\n\n >>> sl = SortedList(\'abcdefghij\')\n >>> it = sl.islice(2, 6)\n >>> list(it)\n [\'c\', \'d\', \'e\', \'f\']\n\n :param int start: start index (inclusive)\n :param int stop: stop index (exclusive)\n :param bool reverse: yield values in reverse order\n :return: iterator\n\n """\n _len = self._len\n\n if not _len:\n return iter(())\n\n start, stop, _ = slice(start, stop).indices(self._len)\n\n if start >= stop:\n return iter(())\n\n _pos = self._pos\n\n min_pos, min_idx = _pos(start)\n\n if stop == _len:\n max_pos = len(self._lists) - 1\n max_idx = len(self._lists[-1])\n else:\n max_pos, max_idx = _pos(stop)\n\n return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)\n\n def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):\n """Return an iterator that slices sorted list using two index pairs.\n\n The index pairs are (min_pos, min_idx) and (max_pos, max_idx), the\n first inclusive and the latter exclusive. See `_pos` for details on how\n an index is converted to an index pair.\n\n When `reverse` is `True`, values are yielded from the iterator in\n reverse order.\n\n """\n _lists = self._lists\n\n if min_pos > max_pos:\n return iter(())\n\n if min_pos == max_pos:\n if reverse:\n indices = reversed(range(min_idx, max_idx))\n return map(_lists[min_pos].__getitem__, indices)\n\n indices = range(min_idx, max_idx)\n return map(_lists[min_pos].__getitem__, indices)\n\n next_pos = min_pos + 1\n\n if next_pos == max_pos:\n if reverse:\n min_indices = range(min_idx, len(_lists[min_pos]))\n max_indices = range(max_idx)\n return chain(\n map(_lists[max_pos].__getitem__, reversed(max_indices)),\n map(_lists[min_pos].__getitem__, reversed(min_indices)),\n )\n\n min_indices = range(min_idx, len(_lists[min_pos]))\n max_indices = range(max_idx)\n return chain(\n map(_lists[min_pos].__getitem__, min_indices),\n map(_lists[max_pos].__getitem__, max_indices),\n )\n\n if reverse:\n min_indices = range(min_idx, len(_lists[min_pos]))\n sublist_indices = range(next_pos, max_pos)\n sublists = map(_lists.__getitem__, reversed(sublist_indices))\n max_indices = range(max_idx)\n return chain(\n map(_lists[max_pos].__getitem__, reversed(max_indices)),\n chain.from_iterable(map(reversed, sublists)),\n map(_lists[min_pos].__getitem__, reversed(min_indices)),\n )\n\n min_indices = range(min_idx, len(_lists[min_pos]))\n sublist_indices = range(next_pos, max_pos)\n sublists = map(_lists.__getitem__, sublist_indices)\n max_indices = range(max_idx)\n return chain(\n map(_lists[min_pos].__getitem__, min_indices),\n chain.from_iterable(sublists),\n map(_lists[max_pos].__getitem__, max_indices),\n )\n\n def irange(self, minimum=None, maximum=None, inclusive=(True, True),\n reverse=False):\n """Create an iterator of values between `minimum` and `maximum`.\n\n Both `minimum` and `maximum` default to `None` which is automatically\n inclusive of the beginning and end of the sorted list.\n\n The argument `inclusive` is a pair of booleans that indicates whether\n the minimum and maximum ought to be included in the range,\n respectively. The default is ``(True, True)`` such that the range is\n inclusive of both minimum and maximum.\n\n When `reverse` is `True` the values are yielded from the iterator in\n reverse order; `reverse` defaults to `False`.\n\n >>> sl = SortedList(\'abcdefghij\')\n >>> it = sl.irange(\'c\', \'f\')\n >>> list(it)\n [\'c\', \'d\', \'e\', \'f\']\n\n :param minimum: minimum value to start iterating\n :param maximum: maximum value to stop iterating\n :param inclusive: pair of booleans\n :param bool reverse: yield values in reverse order\n :return: iterator\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return iter(())\n\n _lists = self._lists\n\n # Calculate the minimum (pos, idx) pair. By default this location\n # will be inclusive in our calculation.\n\n if minimum is None:\n min_pos = 0\n min_idx = 0\n else:\n if inclusive[0]:\n min_pos = bisect_left(_maxes, minimum)\n\n if min_pos == len(_maxes):\n return iter(())\n\n min_idx = bisect_left(_lists[min_pos], minimum)\n else:\n min_pos = bisect_right(_maxes, minimum)\n\n if min_pos == len(_maxes):\n return iter(())\n\n min_idx = bisect_right(_lists[min_pos], minimum)\n\n # Calculate the maximum (pos, idx) pair. By default this location\n # will be exclusive in our calculation.\n\n if maximum is None:\n max_pos = len(_maxes) - 1\n max_idx = len(_lists[max_pos])\n else:\n if inclusive[1]:\n max_pos = bisect_right(_maxes, maximum)\n\n if max_pos == len(_maxes):\n max_pos -= 1\n max_idx = len(_lists[max_pos])\n else:\n max_idx = bisect_right(_lists[max_pos], maximum)\n else:\n max_pos = bisect_left(_maxes, maximum)\n\n if max_pos == len(_maxes):\n max_pos -= 1\n max_idx = len(_lists[max_pos])\n else:\n max_idx = bisect_left(_lists[max_pos], maximum)\n\n return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)\n\n def __len__(self):\n """Return the size of the sorted list.\n\n ``sl.__len__()`` <==> ``len(sl)``\n\n :return: size of sorted list\n\n """\n return self._len\n\n def bisect_left(self, value):\n """Return an index to insert `value` in the sorted list.\n\n If the `value` is already present, the insertion point will be before\n (to the left of) any existing values.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList([10, 11, 12, 13, 14])\n >>> sl.bisect_left(12)\n 2\n\n :param value: insertion index of value in sorted list\n :return: index\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n pos = bisect_left(_maxes, value)\n\n if pos == len(_maxes):\n return self._len\n\n idx = bisect_left(self._lists[pos], value)\n return self._loc(pos, idx)\n\n def bisect_right(self, value):\n """Return an index to insert `value` in the sorted list.\n\n Similar to `bisect_left`, but if `value` is already present, the\n insertion point will be after (to the right of) any existing values.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList([10, 11, 12, 13, 14])\n >>> sl.bisect_right(12)\n 3\n\n :param value: insertion index of value in sorted list\n :return: index\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n pos = bisect_right(_maxes, value)\n\n if pos == len(_maxes):\n return self._len\n\n idx = bisect_right(self._lists[pos], value)\n return self._loc(pos, idx)\n\n bisect = bisect_right\n _bisect_right = bisect_right\n\n def upper_bound(self, x, equal=False):\n k = self.bisect_left(x + equal)\n if k:\n return self[k - 1]\n else:\n sys.stderr.write("upper_bound: no element smaller than {0} in this SortedList\\n".format(x))\n\n def lower_bound(self, x, equal=False):\n k = self.bisect_left(x + 1 - equal) + 1\n if k <= len(self):\n return self[k - 1]\n else:\n sys.stderr.write("lower_bound: no element larger than {0} in this SortedList\\n".format(x))\n\n def count(self, value):\n """Return number of occurrences of `value` in the sorted list.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])\n >>> sl.count(3)\n 3\n\n :param value: value to count in sorted list\n :return: count\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n pos_left = bisect_left(_maxes, value)\n\n if pos_left == len(_maxes):\n return 0\n\n _lists = self._lists\n idx_left = bisect_left(_lists[pos_left], value)\n pos_right = bisect_right(_maxes, value)\n\n if pos_right == len(_maxes):\n return self._len - self._loc(pos_left, idx_left)\n\n idx_right = bisect_right(_lists[pos_right], value)\n\n if pos_left == pos_right:\n return idx_right - idx_left\n\n right = self._loc(pos_right, idx_right)\n left = self._loc(pos_left, idx_left)\n return right - left\n\n def copy(self):\n """Return a shallow copy of the sorted list.\n\n Runtime complexity: `O(n)`\n\n :return: new sorted list\n\n """\n return self.__class__(self)\n\n __copy__ = copy\n\n def append(self, value):\n """Raise not-implemented error.\n\n Implemented to override `MutableSequence.append` which provides an\n erroneous default implementation.\n\n :raises NotImplementedError: use ``sl.add(value)`` instead\n\n """\n raise NotImplementedError(\'use ``sl.add(value)`` instead\')\n\n def extend(self, values):\n """Raise not-implemented error.\n\n Implemented to override `MutableSequence.extend` which provides an\n erroneous default implementation.\n\n :raises NotImplementedError: use ``sl.update(values)`` instead\n\n """\n raise NotImplementedError(\'use ``sl.update(values)`` instead\')\n\n def insert(self, index, value):\n """Raise not-implemented error.\n\n :raises NotImplementedError: use ``sl.add(value)`` instead\n\n """\n raise NotImplementedError(\'use ``sl.add(value)`` instead\')\n\n def pop(self, index=-1):\n """Remove and return value at `index` in sorted list.\n\n Raise :exc:`IndexError` if the sorted list is empty or index is out of\n range.\n\n Negative indices are supported.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList(\'abcde\')\n >>> sl.pop()\n \'e\'\n >>> sl.pop(2)\n \'c\'\n >>> sl\n SortedList([\'a\', \'b\', \'d\'])\n\n :param int index: index of value (default -1)\n :return: value\n :raises IndexError: if index is out of range\n\n """\n if not self._len:\n raise IndexError(\'pop index out of range\')\n\n _lists = self._lists\n\n if index == 0:\n val = _lists[0][0]\n self._delete(0, 0)\n return val\n\n if index == -1:\n pos = len(_lists) - 1\n loc = len(_lists[pos]) - 1\n val = _lists[pos][loc]\n self._delete(pos, loc)\n return val\n\n if 0 <= index < len(_lists[0]):\n val = _lists[0][index]\n self._delete(0, index)\n return val\n\n len_last = len(_lists[-1])\n\n if -len_last < index < 0:\n pos = len(_lists) - 1\n loc = len_last + index\n val = _lists[pos][loc]\n self._delete(pos, loc)\n return val\n\n pos, idx = self._pos(index)\n val = _lists[pos][idx]\n self._delete(pos, idx)\n return val\n\n def index(self, value, start=None, stop=None):\n """Return first index of value in sorted list.\n\n Raise ValueError if `value` is not present.\n\n Index must be between `start` and `stop` for the `value` to be\n considered present. The default value, None, for `start` and `stop`\n indicate the beginning and end of the sorted list.\n\n Negative indices are supported.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> sl = SortedList(\'abcde\')\n >>> sl.index(\'d\')\n 3\n >>> sl.index(\'z\')\n Traceback (most recent call last):\n ...\n ValueError: \'z\' is not in list\n\n :param value: value in sorted list\n :param int start: start index (default None, start of sorted list)\n :param int stop: stop index (default None, end of sorted list)\n :return: index of value\n :raises ValueError: if value is not present\n\n """\n _len = self._len\n\n if not _len:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n if start is None:\n start = 0\n if start < 0:\n start += _len\n if start < 0:\n start = 0\n\n if stop is None:\n stop = _len\n if stop < 0:\n stop += _len\n if stop > _len:\n stop = _len\n\n if stop <= start:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n _maxes = self._maxes\n pos_left = bisect_left(_maxes, value)\n\n if pos_left == len(_maxes):\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n _lists = self._lists\n idx_left = bisect_left(_lists[pos_left], value)\n\n if _lists[pos_left][idx_left] != value:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n stop -= 1\n left = self._loc(pos_left, idx_left)\n\n if start <= left:\n if left <= stop:\n return left\n else:\n right = self._bisect_right(value) - 1\n\n if start <= right:\n return start\n\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n def __add__(self, other):\n """Return new sorted list containing all values in both sequences.\n\n ``sl.__add__(other)`` <==> ``sl + other``\n\n Values in `other` do not need to be in sorted order.\n\n Runtime complexity: `O(n*log(n))`\n\n >>> sl1 = SortedList(\'bat\')\n >>> sl2 = SortedList(\'cat\')\n >>> sl1 + sl2\n SortedList([\'a\', \'a\', \'b\', \'c\', \'t\', \'t\'])\n\n :param other: other iterable\n :return: new sorted list\n\n """\n values = reduce(iadd, self._lists, [])\n values.extend(other)\n return self.__class__(values)\n\n __radd__ = __add__\n\n def __iadd__(self, other):\n """Update sorted list with values from `other`.\n\n ``sl.__iadd__(other)`` <==> ``sl += other``\n\n Values in `other` do not need to be in sorted order.\n\n Runtime complexity: `O(k*log(n))` -- approximate.\n\n >>> sl = SortedList(\'bat\')\n >>> sl += \'cat\'\n >>> sl\n SortedList([\'a\', \'a\', \'b\', \'c\', \'t\', \'t\'])\n\n :param other: other iterable\n :return: existing sorted list\n\n """\n self._update(other)\n return self\n\n def __mul__(self, num):\n """Return new sorted list with `num` shallow copies of values.\n\n ``sl.__mul__(num)`` <==> ``sl * num``\n\n Runtime complexity: `O(n*log(n))`\n\n >>> sl = SortedList(\'abc\')\n >>> sl * 3\n SortedList([\'a\', \'a\', \'a\', \'b\', \'b\', \'b\', \'c\', \'c\', \'c\'])\n\n :param int num: count of shallow copies\n :return: new sorted list\n\n """\n values = reduce(iadd, self._lists, []) * num\n return self.__class__(values)\n\n __rmul__ = __mul__\n\n def __imul__(self, num):\n """Update the sorted list with `num` shallow copies of values.\n\n ``sl.__imul__(num)`` <==> ``sl *= num``\n\n Runtime complexity: `O(n*log(n))`\n\n >>> sl = SortedList(\'abc\')\n >>> sl *= 3\n >>> sl\n SortedList([\'a\', \'a\', \'a\', \'b\', \'b\', \'b\', \'c\', \'c\', \'c\'])\n\n :param int num: count of shallow copies\n :return: existing sorted list\n\n """\n values = reduce(iadd, self._lists, []) * num\n self._clear()\n self._update(values)\n return self\n\n def __make_cmp(seq_op, symbol, doc):\n "Make comparator method."\n\n def comparer(self, other):\n "Compare method for sorted list and sequence."\n if not isinstance(other, Sequence):\n return NotImplemented\n\n self_len = self._len\n len_other = len(other)\n\n if self_len != len_other:\n if seq_op is eq:\n return False\n if seq_op is ne:\n return True\n\n for alpha, beta in zip(self, other):\n if alpha != beta:\n return seq_op(alpha, beta)\n\n return seq_op(self_len, len_other)\n\n seq_op_name = seq_op.__name__\n comparer.__name__ = \'__{0}__\'.format(seq_op_name)\n doc_str = """Return true if and only if sorted list is {0} `other`.\n\n ``sl.__{1}__(other)`` <==> ``sl {2} other``\n\n Comparisons use lexicographical order as with sequences.\n\n Runtime complexity: `O(n)`\n\n :param other: `other` sequence\n :return: true if sorted list is {0} `other`\n\n """\n comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))\n return comparer\n\n __eq__ = __make_cmp(eq, \'==\', \'equal to\')\n __ne__ = __make_cmp(ne, \'!=\', \'not equal to\')\n __lt__ = __make_cmp(lt, \'<\', \'less than\')\n __gt__ = __make_cmp(gt, \'>\', \'greater than\')\n __le__ = __make_cmp(le, \'<=\', \'less than or equal to\')\n __ge__ = __make_cmp(ge, \'>=\', \'greater than or equal to\')\n __make_cmp = staticmethod(__make_cmp)\n\n def __reduce__(self):\n values = reduce(iadd, self._lists, [])\n return (type(self), (values,))\n\n @recursive_repr()\n def __repr__(self):\n """Return string representation of sorted list.\n\n ``sl.__repr__()`` <==> ``repr(sl)``\n\n :return: string representation\n\n """\n return \'{0}({1!r})\'.format(type(self).__name__, list(self))\n\n def _check(self):\n """Check invariants of sorted list.\n\n Runtime complexity: `O(n)`\n\n """\n try:\n assert self._load >= 4\n assert len(self._maxes) == len(self._lists)\n assert self._len == sum(len(sublist) for sublist in self._lists)\n\n # Check all sublists are sorted.\n\n for sublist in self._lists:\n for pos in range(1, len(sublist)):\n assert sublist[pos - 1] <= sublist[pos]\n\n # Check beginning/end of sublists are sorted.\n\n for pos in range(1, len(self._lists)):\n assert self._lists[pos - 1][-1] <= self._lists[pos][0]\n\n # Check _maxes index is the last value of each sublist.\n\n for pos in range(len(self._maxes)):\n assert self._maxes[pos] == self._lists[pos][-1]\n\n # Check sublist lengths are less than double load-factor.\n\n double = self._load << 1\n assert all(len(sublist) <= double for sublist in self._lists)\n\n # Check sublist lengths are greater than half load-factor for all\n # but the last sublist.\n\n half = self._load >> 1\n for pos in range(0, len(self._lists) - 1):\n assert len(self._lists[pos]) >= half\n\n if self._index:\n assert self._len == self._index[0]\n assert len(self._index) == self._offset + len(self._lists)\n\n # Check index leaf nodes equal length of sublists.\n\n for pos in range(len(self._lists)):\n leaf = self._index[self._offset + pos]\n assert leaf == len(self._lists[pos])\n\n # Check index branch nodes are the sum of their children.\n\n for pos in range(self._offset):\n child = (pos << 1) + 1\n if child >= len(self._index):\n assert self._index[pos] == 0\n elif child + 1 == len(self._index):\n assert self._index[pos] == self._index[child]\n else:\n child_sum = self._index[child] + self._index[child + 1]\n assert child_sum == self._index[pos]\n except:\n traceback.print_exc(file=sys.stdout)\n print(\'len\', self._len)\n print(\'load\', self._load)\n print(\'offset\', self._offset)\n print(\'len_index\', len(self._index))\n print(\'index\', self._index)\n print(\'len_maxes\', len(self._maxes))\n print(\'maxes\', self._maxes)\n print(\'len_lists\', len(self._lists))\n print(\'lists\', self._lists)\n raise\n\n\ndef identity(value):\n """Identity function."""\n return value\n\n\nclass OnlineSortedKeyList(OnlineSortedList):\n """Sorted-key list is a subtype of sorted list.\n\n The sorted-key list maintains values in comparison order based on the\n result of a key function applied to every value.\n\n All the same methods that are available in :class:`SortedList` are also\n available in :class:`SortedKeyList`.\n\n Additional methods provided:\n\n * :attr:`SortedKeyList.key`\n * :func:`SortedKeyList.bisect_key_left`\n * :func:`SortedKeyList.bisect_key_right`\n * :func:`SortedKeyList.irange_key`\n\n Some examples below use:\n\n >>> from operator import neg\n >>> neg\n <built-in function neg>\n >>> neg(1)\n -1\n\n """\n\n def __init__(self, iterable=None, key=identity):\n """Initialize sorted-key list instance.\n\n Optional `iterable` argument provides an initial iterable of values to\n initialize the sorted-key list.\n\n Optional `key` argument defines a callable that, like the `key`\n argument to Python\'s `sorted` function, extracts a comparison key from\n each value. The default is the identity function.\n\n Runtime complexity: `O(n*log(n))`\n\n >>> from operator import neg\n >>> skl = SortedKeyList(key=neg)\n >>> skl\n SortedKeyList([], key=<built-in function neg>)\n >>> skl = SortedKeyList([3, 1, 2], key=neg)\n >>> skl\n SortedKeyList([3, 2, 1], key=<built-in function neg>)\n\n :param iterable: initial values (optional)\n :param key: function used to extract comparison key (optional)\n\n """\n super().__init__()\n self._key = key\n self._len = 0\n self._load = self.DEFAULT_LOAD_FACTOR\n self._lists = []\n self._keys = []\n self._maxes = []\n self._index = []\n self._offset = 0\n\n if iterable is not None:\n self._update(iterable)\n\n def __new__(cls, iterable=None, key=identity):\n return object.__new__(cls)\n\n @property\n def key(self):\n "Function used to extract comparison key from values."\n return self._key\n\n def clear(self):\n """Remove all values from sorted-key list.\n\n Runtime complexity: `O(n)`\n\n """\n self._len = 0\n del self._lists[:]\n del self._keys[:]\n del self._maxes[:]\n del self._index[:]\n\n _clear = clear\n\n def add(self, value):\n """Add `value` to sorted-key list.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList(key=neg)\n >>> skl.add(3)\n >>> skl.add(1)\n >>> skl.add(2)\n >>> skl\n SortedKeyList([3, 2, 1], key=<built-in function neg>)\n\n :param value: value to add to sorted-key list\n\n """\n _lists = self._lists\n _keys = self._keys\n _maxes = self._maxes\n\n key = self._key(value)\n\n if _maxes:\n pos = bisect_right(_maxes, key)\n\n if pos == len(_maxes):\n pos -= 1\n _lists[pos].append(value)\n _keys[pos].append(key)\n _maxes[pos] = key\n else:\n idx = bisect_right(_keys[pos], key)\n _lists[pos].insert(idx, value)\n _keys[pos].insert(idx, key)\n\n self._expand(pos)\n else:\n _lists.append([value])\n _keys.append([key])\n _maxes.append(key)\n\n self._len += 1\n\n def _expand(self, pos):\n """Split sublists with length greater than double the load-factor.\n\n Updates the index when the sublist length is less than double the load\n level. This requires incrementing the nodes in a traversal from the\n leaf node to the root. For an example traversal see\n ``SortedList._loc``.\n\n """\n _lists = self._lists\n _keys = self._keys\n _index = self._index\n\n if len(_keys[pos]) > (self._load << 1):\n _maxes = self._maxes\n _load = self._load\n\n _lists_pos = _lists[pos]\n _keys_pos = _keys[pos]\n half = _lists_pos[_load:]\n half_keys = _keys_pos[_load:]\n del _lists_pos[_load:]\n del _keys_pos[_load:]\n _maxes[pos] = _keys_pos[-1]\n\n _lists.insert(pos + 1, half)\n _keys.insert(pos + 1, half_keys)\n _maxes.insert(pos + 1, half_keys[-1])\n\n del _index[:]\n else:\n if _index:\n child = self._offset + pos\n while child:\n _index[child] += 1\n child = (child - 1) >> 1\n _index[0] += 1\n\n def update(self, iterable):\n """Update sorted-key list by adding all values from `iterable`.\n\n Runtime complexity: `O(k*log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList(key=neg)\n >>> skl.update([3, 1, 2])\n >>> skl\n SortedKeyList([3, 2, 1], key=<built-in function neg>)\n\n :param iterable: iterable of values to add\n\n """\n _lists = self._lists\n _keys = self._keys\n _maxes = self._maxes\n values = sorted(iterable, key=self._key)\n\n if _maxes:\n if len(values) * 4 >= self._len:\n _lists.append(values)\n values = reduce(iadd, _lists, [])\n values.sort(key=self._key)\n self._clear()\n else:\n _add = self.add\n for val in values:\n _add(val)\n return\n\n _load = self._load\n _lists.extend(values[pos:(pos + _load)]\n for pos in range(0, len(values), _load))\n _keys.extend(list(map(self._key, _list)) for _list in _lists)\n _maxes.extend(sublist[-1] for sublist in _keys)\n self._len = len(values)\n del self._index[:]\n\n _update = update\n\n def __contains__(self, value):\n """Return true if `value` is an element of the sorted-key list.\n\n ``skl.__contains__(value)`` <==> ``value in skl``\n\n Runtime complexity: `O(log(n))`\n\n >>> from operator import neg\n >>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg)\n >>> 3 in skl\n True\n\n :param value: search for value in sorted-key list\n :return: true if `value` in sorted-key list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return False\n\n key = self._key(value)\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n return False\n\n _lists = self._lists\n _keys = self._keys\n\n idx = bisect_left(_keys[pos], key)\n\n len_keys = len(_keys)\n len_sublist = len(_keys[pos])\n\n while True:\n if _keys[pos][idx] != key:\n return False\n if _lists[pos][idx] == value:\n return True\n idx += 1\n if idx == len_sublist:\n pos += 1\n if pos == len_keys:\n return False\n len_sublist = len(_keys[pos])\n idx = 0\n\n def discard(self, value):\n """Remove `value` from sorted-key list if it is a member.\n\n If `value` is not a member, do nothing.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)\n >>> skl.discard(1)\n >>> skl.discard(0)\n >>> skl == [5, 4, 3, 2]\n True\n\n :param value: `value` to discard from sorted-key list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return\n\n key = self._key(value)\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n return\n\n _lists = self._lists\n _keys = self._keys\n idx = bisect_left(_keys[pos], key)\n len_keys = len(_keys)\n len_sublist = len(_keys[pos])\n\n while True:\n if _keys[pos][idx] != key:\n return\n if _lists[pos][idx] == value:\n self._delete(pos, idx)\n return\n idx += 1\n if idx == len_sublist:\n pos += 1\n if pos == len_keys:\n return\n len_sublist = len(_keys[pos])\n idx = 0\n\n def remove(self, value):\n """Remove `value` from sorted-key list; `value` must be a member.\n\n If `value` is not a member, raise ValueError.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg)\n >>> skl.remove(5)\n >>> skl == [4, 3, 2, 1]\n True\n >>> skl.remove(0)\n Traceback (most recent call last):\n ...\n ValueError: 0 not in list\n\n :param value: `value` to remove from sorted-key list\n :raises ValueError: if `value` is not in sorted-key list\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n raise ValueError(\'{0!r} not in list\'.format(value))\n\n key = self._key(value)\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n raise ValueError(\'{0!r} not in list\'.format(value))\n\n _lists = self._lists\n _keys = self._keys\n idx = bisect_left(_keys[pos], key)\n len_keys = len(_keys)\n len_sublist = len(_keys[pos])\n\n while True:\n if _keys[pos][idx] != key:\n raise ValueError(\'{0!r} not in list\'.format(value))\n if _lists[pos][idx] == value:\n self._delete(pos, idx)\n return\n idx += 1\n if idx == len_sublist:\n pos += 1\n if pos == len_keys:\n raise ValueError(\'{0!r} not in list\'.format(value))\n len_sublist = len(_keys[pos])\n idx = 0\n\n def _delete(self, pos, idx):\n """Delete value at the given `(pos, idx)`.\n\n Combines lists that are less than half the load level.\n\n Updates the index when the sublist length is more than half the load\n level. This requires decrementing the nodes in a traversal from the\n leaf node to the root. For an example traversal see\n ``SortedList._loc``.\n\n :param int pos: lists index\n :param int idx: sublist index\n\n """\n _lists = self._lists\n _keys = self._keys\n _maxes = self._maxes\n _index = self._index\n keys_pos = _keys[pos]\n lists_pos = _lists[pos]\n\n del keys_pos[idx]\n del lists_pos[idx]\n self._len -= 1\n\n len_keys_pos = len(keys_pos)\n\n if len_keys_pos > (self._load >> 1):\n _maxes[pos] = keys_pos[-1]\n\n if _index:\n child = self._offset + pos\n while child > 0:\n _index[child] -= 1\n child = (child - 1) >> 1\n _index[0] -= 1\n elif len(_keys) > 1:\n if not pos:\n pos += 1\n\n prev = pos - 1\n _keys[prev].extend(_keys[pos])\n _lists[prev].extend(_lists[pos])\n _maxes[prev] = _keys[prev][-1]\n\n del _lists[pos]\n del _keys[pos]\n del _maxes[pos]\n del _index[:]\n\n self._expand(prev)\n elif len_keys_pos:\n _maxes[pos] = keys_pos[-1]\n else:\n del _lists[pos]\n del _keys[pos]\n del _maxes[pos]\n del _index[:]\n\n def irange(self, minimum=None, maximum=None, inclusive=(True, True),\n reverse=False):\n """Create an iterator of values between `minimum` and `maximum`.\n\n Both `minimum` and `maximum` default to `None` which is automatically\n inclusive of the beginning and end of the sorted-key list.\n\n The argument `inclusive` is a pair of booleans that indicates whether\n the minimum and maximum ought to be included in the range,\n respectively. The default is ``(True, True)`` such that the range is\n inclusive of both minimum and maximum.\n\n When `reverse` is `True` the values are yielded from the iterator in\n reverse order; `reverse` defaults to `False`.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([11, 12, 13, 14, 15], key=neg)\n >>> it = skl.irange(14.5, 11.5)\n >>> list(it)\n [14, 13, 12]\n\n :param minimum: minimum value to start iterating\n :param maximum: maximum value to stop iterating\n :param inclusive: pair of booleans\n :param bool reverse: yield values in reverse order\n :return: iterator\n\n """\n min_key = self._key(minimum) if minimum is not None else None\n max_key = self._key(maximum) if maximum is not None else None\n return self._irange_key(\n min_key=min_key, max_key=max_key,\n inclusive=inclusive, reverse=reverse,\n )\n\n def irange_key(self, min_key=None, max_key=None, inclusive=(True, True),\n reverse=False):\n """Create an iterator of values between `min_key` and `max_key`.\n\n Both `min_key` and `max_key` default to `None` which is automatically\n inclusive of the beginning and end of the sorted-key list.\n\n The argument `inclusive` is a pair of booleans that indicates whether\n the minimum and maximum ought to be included in the range,\n respectively. The default is ``(True, True)`` such that the range is\n inclusive of both minimum and maximum.\n\n When `reverse` is `True` the values are yielded from the iterator in\n reverse order; `reverse` defaults to `False`.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([11, 12, 13, 14, 15], key=neg)\n >>> it = skl.irange_key(-14, -12)\n >>> list(it)\n [14, 13, 12]\n\n :param min_key: minimum key to start iterating\n :param max_key: maximum key to stop iterating\n :param inclusive: pair of booleans\n :param bool reverse: yield values in reverse order\n :return: iterator\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return iter(())\n\n _keys = self._keys\n\n # Calculate the minimum (pos, idx) pair. By default this location\n # will be inclusive in our calculation.\n\n if min_key is None:\n min_pos = 0\n min_idx = 0\n else:\n if inclusive[0]:\n min_pos = bisect_left(_maxes, min_key)\n\n if min_pos == len(_maxes):\n return iter(())\n\n min_idx = bisect_left(_keys[min_pos], min_key)\n else:\n min_pos = bisect_right(_maxes, min_key)\n\n if min_pos == len(_maxes):\n return iter(())\n\n min_idx = bisect_right(_keys[min_pos], min_key)\n\n # Calculate the maximum (pos, idx) pair. By default this location\n # will be exclusive in our calculation.\n\n if max_key is None:\n max_pos = len(_maxes) - 1\n max_idx = len(_keys[max_pos])\n else:\n if inclusive[1]:\n max_pos = bisect_right(_maxes, max_key)\n\n if max_pos == len(_maxes):\n max_pos -= 1\n max_idx = len(_keys[max_pos])\n else:\n max_idx = bisect_right(_keys[max_pos], max_key)\n else:\n max_pos = bisect_left(_maxes, max_key)\n\n if max_pos == len(_maxes):\n max_pos -= 1\n max_idx = len(_keys[max_pos])\n else:\n max_idx = bisect_left(_keys[max_pos], max_key)\n\n return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)\n\n _irange_key = irange_key\n\n def bisect_left(self, value):\n """Return an index to insert `value` in the sorted-key list.\n\n If the `value` is already present, the insertion point will be before\n (to the left of) any existing values.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)\n >>> skl.bisect_left(1)\n 4\n\n :param value: insertion index of value in sorted-key list\n :return: index\n\n """\n return self._bisect_key_left(self._key(value))\n\n def bisect_right(self, value):\n """Return an index to insert `value` in the sorted-key list.\n\n Similar to `bisect_left`, but if `value` is already present, the\n insertion point will be after (to the right of) any existing values.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedList([5, 4, 3, 2, 1], key=neg)\n >>> skl.bisect_right(1)\n 5\n\n :param value: insertion index of value in sorted-key list\n :return: index\n\n """\n return self._bisect_key_right(self._key(value))\n\n bisect = bisect_right\n\n def bisect_key_left(self, key):\n """Return an index to insert `key` in the sorted-key list.\n\n If the `key` is already present, the insertion point will be before (to\n the left of) any existing keys.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)\n >>> skl.bisect_key_left(-1)\n 4\n\n :param key: insertion index of key in sorted-key list\n :return: index\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n return self._len\n\n idx = bisect_left(self._keys[pos], key)\n\n return self._loc(pos, idx)\n\n _bisect_key_left = bisect_key_left\n\n def bisect_key_right(self, key):\n """Return an index to insert `key` in the sorted-key list.\n\n Similar to `bisect_key_left`, but if `key` is already present, the\n insertion point will be after (to the right of) any existing keys.\n\n Similar to the `bisect` module in the standard library.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedList([5, 4, 3, 2, 1], key=neg)\n >>> skl.bisect_key_right(-1)\n 5\n\n :param key: insertion index of key in sorted-key list\n :return: index\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n pos = bisect_right(_maxes, key)\n\n if pos == len(_maxes):\n return self._len\n\n idx = bisect_right(self._keys[pos], key)\n\n return self._loc(pos, idx)\n\n bisect_key = bisect_key_right\n _bisect_key_right = bisect_key_right\n\n def count(self, value):\n """Return number of occurrences of `value` in the sorted-key list.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([4, 4, 4, 4, 3, 3, 3, 2, 2, 1], key=neg)\n >>> skl.count(2)\n 2\n\n :param value: value to count in sorted-key list\n :return: count\n\n """\n _maxes = self._maxes\n\n if not _maxes:\n return 0\n\n key = self._key(value)\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n return 0\n\n _lists = self._lists\n _keys = self._keys\n idx = bisect_left(_keys[pos], key)\n total = 0\n len_keys = len(_keys)\n len_sublist = len(_keys[pos])\n\n while True:\n if _keys[pos][idx] != key:\n return total\n if _lists[pos][idx] == value:\n total += 1\n idx += 1\n if idx == len_sublist:\n pos += 1\n if pos == len_keys:\n return total\n len_sublist = len(_keys[pos])\n idx = 0\n\n def copy(self):\n """Return a shallow copy of the sorted-key list.\n\n Runtime complexity: `O(n)`\n\n :return: new sorted-key list\n\n """\n return self.__class__(self, key=self._key)\n\n __copy__ = copy\n\n def index(self, value, start=None, stop=None):\n """Return first index of value in sorted-key list.\n\n Raise ValueError if `value` is not present.\n\n Index must be between `start` and `stop` for the `value` to be\n considered present. The default value, None, for `start` and `stop`\n indicate the beginning and end of the sorted-key list.\n\n Negative indices are supported.\n\n Runtime complexity: `O(log(n))` -- approximate.\n\n >>> from operator import neg\n >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)\n >>> skl.index(2)\n 3\n >>> skl.index(0)\n Traceback (most recent call last):\n ...\n ValueError: 0 is not in list\n\n :param value: value in sorted-key list\n :param int start: start index (default None, start of sorted-key list)\n :param int stop: stop index (default None, end of sorted-key list)\n :return: index of value\n :raises ValueError: if value is not present\n\n """\n _len = self._len\n\n if not _len:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n if start is None:\n start = 0\n if start < 0:\n start += _len\n if start < 0:\n start = 0\n\n if stop is None:\n stop = _len\n if stop < 0:\n stop += _len\n if stop > _len:\n stop = _len\n\n if stop <= start:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n _maxes = self._maxes\n key = self._key(value)\n pos = bisect_left(_maxes, key)\n\n if pos == len(_maxes):\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n stop -= 1\n _lists = self._lists\n _keys = self._keys\n idx = bisect_left(_keys[pos], key)\n len_keys = len(_keys)\n len_sublist = len(_keys[pos])\n\n while True:\n if _keys[pos][idx] != key:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n if _lists[pos][idx] == value:\n loc = self._loc(pos, idx)\n if start <= loc <= stop:\n return loc\n elif loc > stop:\n break\n idx += 1\n if idx == len_sublist:\n pos += 1\n if pos == len_keys:\n raise ValueError(\'{0!r} is not in list\'.format(value))\n len_sublist = len(_keys[pos])\n idx = 0\n\n raise ValueError(\'{0!r} is not in list\'.format(value))\n\n def __add__(self, other):\n """Return new sorted-key list containing all values in both sequences.\n\n ``skl.__add__(other)`` <==> ``skl + other``\n\n Values in `other` do not need to be in sorted-key order.\n\n Runtime complexity: `O(n*log(n))`\n\n >>> from operator import neg\n >>> skl1 = SortedKeyList([5, 4, 3], key=neg)\n >>> skl2 = SortedKeyList([2, 1, 0], key=neg)\n >>> skl1 + skl2\n SortedKeyList([5, 4, 3, 2, 1, 0], key=<built-in function neg>)\n\n :param other: other iterable\n :return: new sorted-key list\n\n """\n values = reduce(iadd, self._lists, [])\n values.extend(other)\n return self.__class__(values, key=self._key)\n\n __radd__ = __add__\n\n def __mul__(self, num):\n """Return new sorted-key list with `num` shallow copies of values.\n\n ``skl.__mul__(num)`` <==> ``skl * num``\n\n Runtime complexity: `O(n*log(n))`\n\n >>> from operator import neg\n >>> skl = SortedKeyList([3, 2, 1], key=neg)\n >>> skl * 2\n SortedKeyList([3, 3, 2, 2, 1, 1], key=<built-in function neg>)\n\n :param int num: count of shallow copies\n :return: new sorted-key list\n\n """\n values = reduce(iadd, self._lists, []) * num\n return self.__class__(values, key=self._key)\n\n def __reduce__(self):\n values = reduce(iadd, self._lists, [])\n return (type(self), (values, self.key))\n\n @recursive_repr()\n def __repr__(self):\n """Return string representation of sorted-key list.\n\n ``skl.__repr__()`` <==> ``repr(skl)``\n\n :return: string representation\n\n """\n type_name = type(self).__name__\n return \'{0}({1!r}, key={2!r})\'.format(type_name, list(self), self._key)\n\n def _check(self):\n """Check invariants of sorted-key list.\n\n Runtime complexity: `O(n)`\n\n """\n try:\n assert self._load >= 4\n assert len(self._maxes) == len(self._lists) == len(self._keys)\n assert self._len == sum(len(sublist) for sublist in self._lists)\n\n # Check all sublists are sorted.\n\n for sublist in self._keys:\n for pos in range(1, len(sublist)):\n assert sublist[pos - 1] <= sublist[pos]\n\n # Check beginning/end of sublists are sorted.\n\n for pos in range(1, len(self._keys)):\n assert self._keys[pos - 1][-1] <= self._keys[pos][0]\n\n # Check _keys matches _key mapped to _lists.\n\n for val_sublist, key_sublist in zip(self._lists, self._keys):\n assert len(val_sublist) == len(key_sublist)\n for val, key in zip(val_sublist, key_sublist):\n assert self._key(val) == key\n\n # Check _maxes index is the last value of each sublist.\n\n for pos in range(len(self._maxes)):\n assert self._maxes[pos] == self._keys[pos][-1]\n\n # Check sublist lengths are less than double load-factor.\n\n double = self._load << 1\n assert all(len(sublist) <= double for sublist in self._lists)\n\n # Check sublist lengths are greater than half load-factor for all\n # but the last sublist.\n\n half = self._load >> 1\n for pos in range(0, len(self._lists) - 1):\n assert len(self._lists[pos]) >= half\n\n if self._index:\n assert self._len == self._index[0]\n assert len(self._index) == self._offset + len(self._lists)\n\n # Check index leaf nodes equal length of sublists.\n\n for pos in range(len(self._lists)):\n leaf = self._index[self._offset + pos]\n assert leaf == len(self._lists[pos])\n\n # Check index branch nodes are the sum of their children.\n\n for pos in range(self._offset):\n child = (pos << 1) + 1\n if child >= len(self._index):\n assert self._index[pos] == 0\n elif child + 1 == len(self._index):\n assert self._index[pos] == self._index[child]\n else:\n child_sum = self._index[child] + self._index[child + 1]\n assert child_sum == self._index[pos]\n except:\n traceback.print_exc(file=sys.stdout)\n print(\'len\', self._len)\n print(\'load\', self._load)\n print(\'offset\', self._offset)\n print(\'len_index\', len(self._index))\n print(\'index\', self._index)\n print(\'len_maxes\', len(self._maxes))\n print(\'maxes\', self._maxes)\n print(\'len_keys\', len(self._keys))\n print(\'keys\', self._keys)\n print(\'len_lists\', len(self._lists))\n print(\'lists\', self._lists)\n raise\n\n\n'), 'lib.string_search': (False, "import functools\nimport typing\n\n\ndef _sa_naive(s: typing.List[int]) -> typing.List[int]:\n sa = list(range(len(s)))\n return sorted(sa, key=lambda i: s[i:])\n\n\ndef _sa_doubling(s: typing.List[int]) -> typing.List[int]:\n n = len(s)\n sa = list(range(n))\n rnk = s.copy()\n tmp = [0] * n\n k = 1\n while k < n:\n def cmp(x: int, y: int) -> int:\n if rnk[x] != rnk[y]:\n return rnk[x] - rnk[y]\n rx = rnk[x + k] if x + k < n else -1\n ry = rnk[y + k] if y + k < n else -1\n return rx - ry\n sa.sort(key=functools.cmp_to_key(cmp))\n tmp[sa[0]] = 0\n for i in range(1, n):\n tmp[sa[i]] = tmp[sa[i - 1]] + (1 if cmp(sa[i - 1], sa[i]) else 0)\n tmp, rnk = rnk, tmp\n k *= 2\n return sa\n\n\ndef _sa_is(s: typing.List[int], upper: int) -> typing.List[int]:\n threshold_naive = 10\n threshold_doubling = 40\n\n n = len(s)\n\n if n == 0:\n return []\n if n == 1:\n return [0]\n if n == 2:\n if s[0] < s[1]:\n return [0, 1]\n else:\n return [1, 0]\n\n if n < threshold_naive:\n return _sa_naive(s)\n if n < threshold_doubling:\n return _sa_doubling(s)\n\n sa = [0] * n\n ls = [False] * n\n for i in range(n - 2, -1, -1):\n if s[i] == s[i + 1]:\n ls[i] = ls[i + 1]\n else:\n ls[i] = s[i] < s[i + 1]\n\n sum_l = [0] * (upper + 1)\n sum_s = [0] * (upper + 1)\n for i in range(n):\n if not ls[i]:\n sum_s[s[i]] += 1\n else:\n sum_l[s[i] + 1] += 1\n for i in range(upper + 1):\n sum_s[i] += sum_l[i]\n if i < upper:\n sum_l[i + 1] += sum_s[i]\n\n def induce(lms: typing.List[int]) -> None:\n nonlocal sa\n sa = [-1] * n\n\n buf = sum_s.copy()\n for d in lms:\n if d == n:\n continue\n sa[buf[s[d]]] = d\n buf[s[d]] += 1\n\n buf = sum_l.copy()\n sa[buf[s[n - 1]]] = n - 1\n buf[s[n - 1]] += 1\n for i in range(n):\n v = sa[i]\n if v >= 1 and not ls[v - 1]:\n sa[buf[s[v - 1]]] = v - 1\n buf[s[v - 1]] += 1\n\n buf = sum_l.copy()\n for i in range(n - 1, -1, -1):\n v = sa[i]\n if v >= 1 and ls[v - 1]:\n buf[s[v - 1] + 1] -= 1\n sa[buf[s[v - 1] + 1]] = v - 1\n\n lms_map = [-1] * (n + 1)\n m = 0\n for i in range(1, n):\n if not ls[i - 1] and ls[i]:\n lms_map[i] = m\n m += 1\n lms = []\n for i in range(1, n):\n if not ls[i - 1] and ls[i]:\n lms.append(i)\n\n induce(lms)\n\n if m:\n sorted_lms = []\n for v in sa:\n if lms_map[v] != -1:\n sorted_lms.append(v)\n rec_s = [0] * m\n rec_upper = 0\n rec_s[lms_map[sorted_lms[0]]] = 0\n for i in range(1, m):\n left = sorted_lms[i - 1]\n right = sorted_lms[i]\n if lms_map[left] + 1 < m:\n end_l = lms[lms_map[left] + 1]\n else:\n end_l = n\n if lms_map[right] + 1 < m:\n end_r = lms[lms_map[right] + 1]\n else:\n end_r = n\n\n same = True\n if end_l - left != end_r - right:\n same = False\n else:\n while left < end_l:\n if s[left] != s[right]:\n break\n left += 1\n right += 1\n if left == n or s[left] != s[right]:\n same = False\n\n if not same:\n rec_upper += 1\n rec_s[lms_map[sorted_lms[i]]] = rec_upper\n\n rec_sa = _sa_is(rec_s, rec_upper)\n\n for i in range(m):\n sorted_lms[i] = lms[rec_sa[i]]\n induce(sorted_lms)\n\n return sa\n\n\ndef suffix_array(s: typing.Union[str, typing.List[int]],\n upper: typing.Optional[int] = None) -> typing.List[int]:\n '''\n SA-IS, linear-time suffix array construction\n Reference:\n G. Nong, S. Zhang, and W. H. Chan,\n Two Efficient Algorithms for Linear Time Suffix Array Construction\n '''\n\n if isinstance(s, str):\n return _sa_is([ord(c) for c in s], 255)\n elif upper is None:\n n = len(s)\n idx = list(range(n))\n\n def cmp(left: int, right: int) -> int:\n return typing.cast(int, s[left]) - typing.cast(int, s[right])\n\n idx.sort(key=functools.cmp_to_key(cmp))\n s2 = [0] * n\n now = 0\n for i in range(n):\n if i and s[idx[i - 1]] != s[idx[i]]:\n now += 1\n s2[idx[i]] = now\n return _sa_is(s2, now)\n else:\n assert 0 <= upper\n for d in s:\n assert 0 <= d <= upper\n\n return _sa_is(s, upper)\n\n\ndef lcp_array(s: typing.Union[str, typing.List[int]],\n sa: typing.List[int]) -> typing.List[int]:\n '''\n Longest-Common-Prefix computation\n Reference:\n T. Kasai, G. Lee, H. Arimura, S. Arikawa, and K. Park,\n Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its\n Applications\n '''\n\n if isinstance(s, str):\n s = [ord(c) for c in s]\n\n n = len(s)\n assert n >= 1\n\n rnk = [0] * n\n for i in range(n):\n rnk[sa[i]] = i\n\n lcp = [0] * (n - 1)\n h = 0\n for i in range(n):\n if h > 0:\n h -= 1\n if rnk[i] == 0:\n continue\n j = sa[rnk[i] - 1]\n while j + h < n and i + h < n:\n if s[j + h] != s[i + h]:\n break\n h += 1\n lcp[rnk[i] - 1] = h\n\n return lcp\n\n\ndef z_algorithm(s: typing.Union[str, typing.List[int]]) -> typing.List[int]:\n '''\n Z algorithm\n Reference:\n D. Gusfield,\n Algorithms on Strings, Trees, and Sequences: Computer Science and\n Computational Biology\n '''\n\n if isinstance(s, str):\n s = [ord(c) for c in s]\n\n n = len(s)\n if n == 0:\n return []\n\n z = [0] * n\n j = 0\n for i in range(1, n):\n z[i] = 0 if j + z[j] <= i else min(j + z[j] - i, z[i - j])\n while i + z[i] < n and s[z[i]] == s[i + z[i]]:\n z[i] += 1\n if j + z[j] < i + z[i]:\n j = i\n z[0] = n\n\n return z"), 'lib.transform': (False, 'from cmath import rect, pi\nfrom lib.misc import reverse_bits32\nfrom lib.number_theory import totient_factors, primitive_root, modinv, modpow\nfrom typing import List, TypeVar, Callable\n\nM = TypeVar(\'M\')\n\n\ndef fft(a: List[float], inverse=False):\n one = complex(1.0)\n n = (len(a) - 1).bit_length()\n m = 2 ** n\n a += [complex(0.0)] * (m - len(a))\n pows = [rect(1.0, (-pi if inverse else pi) / (2 ** (n - 1)))]\n for _ in range(n - 1):\n pows.append(pows[-1] ** 2)\n pows.reverse()\n\n shift = 32 - n\n for i in range(m):\n j = reverse_bits32(i) >> shift\n if i < j:\n a[i], a[j] = a[j], a[i]\n\n for i in range(m):\n b = 1\n for w1 in pows:\n if not i & b:\n break\n i ^= b\n w = one\n while not i & b:\n s = a[i]\n t = a[i | b] * w\n a[i] = s + t\n a[i | b] = s - t\n w *= w1\n i += 1\n i ^= b\n b <<= 1\n if inverse:\n c = 1 / m\n for i in range(m):\n a[i] *= c\n return a\n\n\ndef ntt(a: List[int], mod: int, inverse: bool = False):\n if type(a[0]) is not int:\n for i, v in enumerate(a):\n a[i] = int(v)\n n = (len(a) - 1).bit_length()\n d2 = 0\n r = 1\n phi_factors = tuple(totient_factors(mod))\n for p in phi_factors:\n if p == 2:\n d2 += 1\n else:\n r *= p\n if d2 < n:\n raise ValueError(f\'Given array is too long: modulo {mod} only support array length up to {2 ** d2}\')\n\n pr = primitive_root(mod, phi_factors)\n if inverse:\n pr = modinv(pr, mod)\n pows = [modpow(pr, r * 2 ** (d2 - n), mod)]\n for _ in range(n - 1):\n pows.append(pows[-1] ** 2 % mod)\n pows = tuple(reversed(pows))\n\n m = 2 ** n\n a.extend(0 for _ in range(m - len(a)))\n\n shift = 32 - n\n for i in range(m):\n j = reverse_bits32(i) >> shift\n if i < j:\n a[i], a[j] = a[j], a[i]\n\n for i in range(m):\n b = 1\n for w1 in pows:\n if not i & b:\n break\n i ^= b\n w = 1\n while not i & b:\n j = i | b\n s = a[i]\n t = a[j] * w\n a[i] = (s + t) % mod\n a[j] = (s - t) % mod\n w = (w * w1) % mod\n i += 1\n i ^= b\n b <<= 1\n\n if inverse:\n c = modinv(m, mod)\n for i, v in enumerate(a):\n a[i] = (v * c) % mod\n return a\n\n\ndef zeta(data: List[M], operator: Callable[[M, M], M]) -> List[M]:\n r"""\n ??????data????????\n\n ``M`` ?????\n\n ``ouput[i] = sum(data[j] : i|j == i)``\n\n ???: ``O(N * log N)``\n\n ?:\n\n ``zeta(data, add)``: ???????????\n\n ``zeta(data, sub)``: ?????????????????\n\n ??->??->???: ``output[k] = sum(a[i]*b[j] : i|j == k)``\n """\n n = len(data)\n i = 1\n while i < n:\n for j in range(n):\n if j & i != 0:\n data[j] = operator(data[j], data[j ^ i])\n i <<= 1\n return data\n\n\ndef zeta_divisors(data: List[M], operator: Callable[[M, M], M]) -> List[M]:\n r"""\n ??????data????????\n\n ``M`` ?????\n\n ``ouput[i] = sum(data[j] for j in range(N) if j?i???)``\n\n ???: ``O(N * log log N)``\n\n ?:\n\n ``zeta_divisors(data, add)``: ?????????\n\n ``mobius_divisors(data, sub)``: ???????????????\n\n ??->??->???: ``output[k] = sum(a[i]*b[j] : lcm(i,j) == k)``\n """\n n = len(data)\n sieve = [0] * len(data)\n for p in range(2, n):\n if not sieve[p]:\n for a, b in zip(range(1, n), range(p, n, p)):\n sieve[b] = 1\n data[b] = operator(data[b], data[a])\n return data\n\n\ndef mobius_divisors(data: List[M], operator: Callable[[M, M], M]) -> List[M]:\n r"""\n ??????data????????\n\n ``zeta_divisors`` ????\n """\n n = len(data)\n sieve = [0] * len(data)\n for p in range(2, n):\n if not sieve[p]:\n t = (n - 1) // p\n for a, b in zip(range(t, 0, -1), range(t * p, 0, -p)):\n sieve[b] = 1\n data[b] = operator(data[b], data[a])\n return data\n\n\ndef zeta_multiples(data: List[M], operator: Callable[[M, M], M]) -> List[M]:\n r"""\n ??????data????????\n\n ``M`` ?????\n\n ``ouput[i] = sum(data[j] for j in range(N) if j?i???)``\n\n ???: ``O(N * log log N)``\n\n ?:\n\n ``zeta_multiple(data, add)``: ?????????\n\n ``mobius_multiples(data, sub)``: ???????????????\n\n ??->??->???: ``output[k] = sum(a[i]*b[j] : gcd(i,j) == k)``\n """\n n = len(data)\n sieve = [0] * len(data)\n for p in range(2, n):\n if not sieve[p]:\n t = (n - 1) // p\n for a, b in zip(range(t, 0, -1), range(t * p, 0, -p)):\n sieve[b] = 1\n data[a] = operator(data[a], data[b])\n return data\n\n\ndef mobius_multiples(data: List[M], operator: Callable[[M, M], M]) -> List[M]:\n r"""\n ??????data????????\n\n ``zeta_multiples`` ????\n """\n n = len(data)\n sieve = [0] * len(data)\n for p in range(2, n):\n if not sieve[p]:\n for a, b in zip(range(1, n), range(p, n, p)):\n sieve[b] = 1\n data[a] = operator(data[a], data[b])\n return data\n'), 'lib.tree': (False, 'from lib.graph import BaseGraph, Graph\nfrom typing import *\nimport itertools\nimport random\nfrom lib.array2d import Array2d\n\n\nT = TypeVar(\'T\')\n\n\nclass BaseRootedTree(BaseGraph):\n\n def __init__(self, n_vertices, root_vertex=0):\n super().__init__(n_vertices)\n self.root = root_vertex\n\n def parent(self, v: int) -> int:\n raise NotImplementedError\n\n def children(self, v: int) -> Iterable[int]:\n raise NotImplementedError\n\n def adj(self, v) -> Iterable[int]:\n if self.root == v:\n return self.children(v)\n return itertools.chain(self.children(v), (self.parent(v),))\n\n def post_order(self) -> Iterable[int]:\n """\n bottom vertices first\n """\n return (~v for v in self.prepost_order() if v < 0)\n\n def pre_order(self) -> Iterable[int]:\n """\n top vertices first\n """\n stack = [self.root]\n while stack:\n v = stack.pop()\n yield v\n for u in self.children(v):\n stack.append(u)\n\n def prepost_order(self) -> Iterable[int]:\n """\n if v >= 0: it\'s pre-order entry.\n\n otherwise: it\'s post-order entry.\n """\n stack = [~self.root, self.root]\n while stack:\n v = stack.pop()\n yield v\n if v >= 0:\n for u in self.children(v):\n stack.append(~u)\n stack.append(u)\n\n def prepost_indices(self, order=None) -> Tuple[List[int], List[int]]:\n if order is None:\n order = self.prepost_order()\n pre_ind = [0] * self.n_vertices\n post_ind = [0] * self.n_vertices\n for i, t in enumerate(order):\n if t >= 0:\n pre_ind[t] = i\n else:\n post_ind[~t] = i\n return pre_ind, post_ind\n\n def depth(self) -> List[int]:\n depth = [0] * self.n_vertices\n for v in self.pre_order():\n d = depth[v]\n for c in self.children(v):\n depth[c] = d + 1\n return depth\n\n def sort_edge_values(self, wedges: Iterable[Tuple[int, int, T]], default: Optional[T] = None) -> List[T]:\n memo = [default] * self.n_vertices\n for u, v, d in wedges:\n if self.parent(u) == v:\n memo[u] = d\n else:\n memo[v] = d\n return memo\n\n def height(self, depth_list: Optional[List[int]] = None) -> int:\n if depth_list is None:\n depth_list = self.depth()\n return max(depth_list) + 1\n\n def path_to_ancestor(self, v: int, k: int) -> List[int]:\n """\n ??v??k???????????.\n\n :param v: ??\n :param k: ??????????\n :return: ??\n """\n res = [-1] * (k + 1)\n for i in range(k + 1):\n res[i] = v\n v = self.parent(v)\n if v < 0:\n break\n return res\n\n def path(self, s: int, t: int, depth_list: Optional[List[int]] = None) -> List[int]:\n """\n ??s????t?????????\n\n :param s: ??\n :param t: ??\n :param depth_list: ?????????\u3000(optional)\n :return: ??\n """\n if s == t:\n return [s]\n if depth_list:\n d1 = depth_list[s]\n d2 = depth_list[t]\n else:\n d1 = 0\n v = s\n while v >= 0:\n v = self.parent(v)\n d1 += 1\n d2 = 0\n v = t\n while v >= 0:\n v = self.parent(v)\n d2 += 1\n p1 = [s]\n p2 = [t]\n if d1 > d2:\n for _ in range(d1 - d2):\n p1.append(self.parent(p1[-1]))\n else:\n for _ in range(d2 - d1):\n p2.append(self.parent(p2[-1]))\n while p1[-1] != p2[-1]:\n p1.append(self.parent(p1[-1]))\n p2.append(self.parent(p2[-1]))\n p2.pop()\n p1.extend(reversed(p2))\n return p1\n\n def aggregate_root_path(self, aggregate: Callable[[T, int], T], identity: T,\n pre_order: Optional[Iterable[int]] = None) -> List[T]:\n """\n ????????????dp??????.\n\n :param aggregate: (T, V) -> T\n :param identity: ???\n :param pre_order: pre_order????\n :return ?????????????dp?\n """\n if pre_order is None:\n pre_order = self.pre_order()\n\n dp = [identity] * self.n_vertices\n for v in pre_order:\n p = self.parent(v)\n if p >= 0:\n dp[v] = aggregate(dp[p], v)\n return dp\n\n def aggregate_subtree(self, merge: Callable[[int, Callable[[None], Iterator[T]]], T],\n post_order: Optional[Iterable[int]] = None) -> List[T]:\n """\n ???????????????dp??????.\n\n :param merge: (vertex, Iterable(T)) -> T, (T, merge)?????\n :param post_order: post_order????\n :return ???????????????????dp?\n """\n if post_order is None:\n post_order = self.post_order()\n\n dp = [None] * self.n_vertices\n for v in post_order:\n dp[v] = merge(v, lambda: (dp[u] for u in self.children(v)))\n return dp\n\n def solve_rerooting(self, merge: Callable[[T, T, int], T], identity: T, finalize: Callable[[T, int, int], T],\n pre_order: Optional[Iterable[int]] = None) -> List[T]:\n """\n ????dp????\n\n dp[u,v] = finalize(merge(dp[v,k] for k in adj[v] if k != u, v), u, v)\n\n (v?????u?????????????????)\n\n :param merge: (T, T, V) -> T, (T, merge)?????\n :param identity: ???\n :param finalize: (T, V, V) -> T\n :param pre_order: pre_order????\n :return ???????????????dp?\n """\n\n if pre_order is None:\n pre_order = list(self.pre_order())\n dp1 = [identity] * self.n_vertices\n dp2 = [identity] * self.n_vertices\n\n for v in reversed(pre_order):\n t = identity\n for u in self.children(v):\n dp2[u] = t\n t = merge(t, finalize(dp1[u], v, u), v)\n t = identity\n for u in reversed(list(self.children(v))):\n dp2[u] = merge(t, dp2[u], v)\n t = merge(t, finalize(dp1[u], v, u), v)\n dp1[v] = t\n for v in pre_order:\n if v == self.root:\n continue\n p = self.parent(v)\n dp2[v] = finalize(merge(dp2[v], dp2[p], v), v, p)\n dp1[v] = merge(dp1[v], dp2[v], v)\n return dp1\n\n def subtree_sizes(self, post_order: Optional[Iterable[int]] = None):\n def merge(v, values):\n return sum(values)+1\n return self.aggregate_subtree(merge, post_order)\n\n def get_doubling_strategy(self):\n return DoublingStrategy(self)\n\n\nclass DoublingStrategy:\n def __init__(self, tree: BaseRootedTree, depth=None, pre_order=None):\n if pre_order is None:\n pre_order = tree.pre_order()\n if depth is None:\n depth = tree.depth()\n self.depth = depth\n self.tree = tree\n d = (max(depth) + 1).bit_length()\n dbl = Array2d.full(tree.n_vertices, d, -1)\n for v in pre_order:\n u = tree.parent(v)\n dbl[v, 0] = u\n for i in range(d - 1):\n u = dbl[u, i]\n if u < 0:\n break\n dbl[v, i + 1] = u\n self.dbl = dbl\n\n def ancestor_of(self, v: int, k: int) -> int:\n if k > self.depth[v]:\n return -1\n i = 0\n while k:\n if k & 1:\n v = self.dbl[v, i]\n k //= 2\n i += 1\n return v\n\n def lca(self, u: int, v: int) -> int:\n lu, lv = self.depth[u], self.depth[v]\n if lu > lv:\n u = self.ancestor_of(u, lu - lv)\n else:\n v = self.ancestor_of(v, lv - lu)\n if u == v:\n return u\n\n i = self.dbl.m - 1\n while True:\n while i >= 0 and self.dbl[u, i] == self.dbl[v, i]:\n i -= 1\n if i < 0:\n return self.dbl[u, 0]\n u, v = self.dbl[u, i], self.dbl[v, i]\n\n def dist(self, u: int, v: int) -> int:\n return self.depth[u] + self.depth[v] - 2 * self.depth[self.lca(u, v)]\n\n\nclass RootedTree(BaseRootedTree):\n\n def __init__(self, parent: List[int], children: Graph, root_vertex: int):\n super().__init__(len(parent), root_vertex)\n self._parent = parent\n self._children = children\n\n @classmethod\n def from_edges(cls, edges, root_vertex=0):\n n = len(edges) + 1\n g = Graph.from_undirected_edges(n, edges)\n parent = [0] * n\n parent[root_vertex] = -1\n stack = [root_vertex]\n while stack:\n v = stack.pop()\n p = parent[v]\n for u in g.adj(v):\n if u != p:\n parent[u] = v\n stack.append(u)\n return cls.from_parent(parent, root_vertex)\n\n @classmethod\n def from_parent(cls, parent, root_vertex=0):\n return cls(parent,\n Graph.from_directed_edges(len(parent), ((p, v) for v, p in enumerate(parent) if p >= 0)),\n root_vertex)\n\n @classmethod\n def random(cls, n_vertices, root_vertex=0):\n parent = [-1] * n_vertices\n vertices = list(range(root_vertex)) + list(range(root_vertex + 1, n_vertices))\n random.shuffle(vertices)\n vertices.append(root_vertex)\n for i, v in zip(reversed(range(n_vertices)), vertices[-2::-1]):\n parent[v] = vertices[random.randrange(i, n_vertices)]\n return cls.from_parent(parent, root_vertex)\n\n def parent(self, v):\n return self._parent[v]\n\n def children(self, v):\n return self._children.adj(v)\n\n\nclass BinaryTrie:\n class Node:\n def __init__(self):\n self.zero = None\n self.one = None\n self.cnt = 0\n\n def __init__(self, bits):\n self.root = self.Node()\n self.bits = bits\n\n def add(self, v):\n n = self.root\n n.cnt += 1\n for d in reversed(range(self.bits)):\n if (v >> d) & 1:\n if not n.one:\n n.one = BinaryTrie.Node()\n n = n.one\n else:\n if not n.zero:\n n.zero = BinaryTrie.Node()\n n = n.zero\n n.cnt += 1\n return n\n\n def remove(self, v):\n n = self.root\n n.cnt -= 1\n for d in reversed(range(self.bits)):\n if (v >> d) & 1:\n n = n.one\n else:\n n = n.zero\n n.cnt -= 1\n return n\n\n def find_argminxor(self, v):\n n = self.root\n r = 0\n for d in reversed(range(self.bits)):\n if (v >> d) & 1:\n if n.one and n.one.cnt > 0:\n n = n.one\n r |= 1 << d\n else:\n n = n.zero\n else:\n if n.zero and n.zero.cnt > 0:\n n = n.zero\n else:\n n = n.one\n r |= 1 << d\n return r\n\n def find_nth(self):\n raise NotImplementedError\n\n def __contains__(self, v):\n n = self.root\n for d in reversed(range(self.bits)):\n if (v >> d) & 1:\n n = n.one\n else:\n n = n.zero\n if not n or n.cnt == 0:\n return False\n return True\n\n\nclass Trie(BaseRootedTree):\n\n def __init__(self, n_alphabets: int):\n super().__init__(1)\n self.n_alphabets = n_alphabets\n self._parent = [-1]\n self.end = [0]\n self._children = [[-1]*n_alphabets]\n\n def add(self, s):\n v = 0\n for c in s:\n u = self._children[v][c]\n if u < 0:\n self._parent.append(v)\n self.end.append(0)\n self._children[v][c] = self.n_vertices\n self._children.append([-1]*self.n_alphabets)\n self.n_vertices += 1\n v = self._children[v][c]\n self.end[v] = 1\n return v\n\n def parent(self, v: int) -> int:\n return self._parent[v]\n\n def children(self, v):\n return (self._children[v][c] for c in range(self.n_alphabets) if self._children[v][c] >= 0)'), 'lib._modint': (False, 'from lib.number_theory import modinv, modpow\n\nintadd = int.__add__\nintsub = int.__sub__\nintmul = int.__mul__\n\n\nclass ModInt(int):\n mod = MOD\n\n @classmethod\n def v(cls, v):\n return ModInt(v % MOD)\n\n def __neg__(self):\n return ModInt(intsub(MOD, self) if self != 0 else 0)\n\n def __add__(self, other):\n x = intadd(self, other)\n return ModInt(x if x < MOD else x - MOD)\n\n def __sub__(self, other):\n x = intsub(self, other)\n return ModInt(x if x >= 0 else x + MOD)\n\n def __rsub__(self, other):\n x = intsub(other, self)\n return ModInt(x if x >= 0 else x + MOD)\n\n def __mul__(self, other):\n return ModInt(intmul(self, other) % MOD)\n\n def __truediv__(self, other):\n return self * ModInt(other).inv\n\n def __rtruediv__(self, other):\n return self.inv * other\n\n __radd__ = __add__\n __rmul__ = __mul__\n __floordiv__ = __truediv__\n __rfloordiv__ = __rtruediv__\n\n def __pow__(self, other, **kwargs):\n return ModInt(modpow(int(self), int(other), MOD))\n\n @property\n def inv(self):\n return ModInt(modinv(int(self), MOD))\n\n @classmethod\n def sum(cls, iterable):\n r = 0\n for v in iterable:\n r += int(v)\n return ModInt(r)\n\n @classmethod\n def product(cls, iterable):\n r = ModInt(1)\n for v in iterable:\n r *= v\n return r\n'), 'lib': (True, ''), } _sys.meta_path.insert(2, InlineImporter) # Entrypoint from collections import defaultdict from lib.data_structure import SegmentTree, BinaryIndexedTree from lib.misc import min2 q = int(input()) queries = [tuple(map(int,input().split())) for _ in range(q)] i2v = sorted(set(tokens[1] for tokens in queries if tokens[0] < 3)) v2i = {v:i for i,v in enumerate(i2v)} bit = BinaryIndexedTree(len(i2v)) memo = defaultdict(int) seg = SegmentTree.all_identity(min2, 2**30, len(i2v)) dup_cnt = 0 for tokens in queries: if tokens[0] == 1: x = tokens[1] if memo[x] == 0: i = v2i[x] s = bit[:i] l = bit.bisect_left(s) if s > 0 else -1 if 0<=l: seg[l] = i2v[l]^x r = bit.bisect_right(s) if r < len(i2v): seg[i] = i2v[r]^x bit[i] += 1 else: dup_cnt += 1 memo[x] += 1 elif tokens[0] == 2: x = tokens[1] if memo[x] == 1: i = v2i[x] bit[i] -= 1 seg[i] = 2**30 s = bit[:i] l = bit.bisect_left(s) if s > 0 else -1 r = bit.bisect_right(s) if 0<=l: if r < len(i2v): seg[l] = i2v[l]^i2v[r] else: seg[l] = 2**30 elif memo[x] == 2: dup_cnt -= 1 memo[x] -= 1 else: print(seg[:] if dup_cnt == 0 else 0)
ConDefects/ConDefects/Code/abc308_g/Python/43737866
condefects-python_data_2516
T = int(input()) INF = float("inf") def check(a,b,c): if abs(a-b) % 3 == 0: d = abs(a-b) // 3 if d <= c: return max(a,b) return INF for t in range(T): R, G, B = map(int, input().split()) ans = [] if R==G or G==B or B==R: rgb = sorted([R,G,B]) print(rgb[1]) else: ans.append( check(R, G, B) ) ans.append( check(R, B, G) ) ans.append( check(B, G, R) ) #print(ans) print(-1) if min(ans)==INF else print(min(ans)) T = int(input()) INF = float("inf") def check(a,b,c): if abs(a-b) % 3 == 0: return max(a,b) return INF for t in range(T): R, G, B = map(int, input().split()) ans = [] if R==G or G==B or B==R: rgb = sorted([R,G,B]) print(rgb[1]) else: ans.append( check(R, G, B) ) ans.append( check(R, B, G) ) ans.append( check(B, G, R) ) #print(ans) print(-1) if min(ans)==INF else print(min(ans))
ConDefects/ConDefects/Code/arc128_b/Python/38862798
condefects-python_data_2517
# B - Balls of Three Colors MAX = 10 ** 8 def solve(r, g, b): def solve1(other1, other2): diff = other1 - other2 if diff % 3 != 0: return MAX return other2 + diff ans = MAX ans = min(ans, solve1(max(g, b), min(g, b))) ans = min(ans, solve1(max(r, b), min(r, b))) ans = min(ans, solve1(max(g, r), min(g, r))) return -1 if ans == MAX else ans t = int(input()) for _ in range(t): r, g, b = [int(e) for e in input().split()] print(solve(r, g, b)) # B - Balls of Three Colors MAX = 10 ** 8 + 1 def solve(r, g, b): def solve1(other1, other2): diff = other1 - other2 if diff % 3 != 0: return MAX return other2 + diff ans = MAX ans = min(ans, solve1(max(g, b), min(g, b))) ans = min(ans, solve1(max(r, b), min(r, b))) ans = min(ans, solve1(max(g, r), min(g, r))) return -1 if ans == MAX else ans t = int(input()) for _ in range(t): r, g, b = [int(e) for e in input().split()] print(solve(r, g, b))
ConDefects/ConDefects/Code/arc128_b/Python/42302488
condefects-python_data_2518
from math import gcd import sys input = sys.stdin.readline inf = float('inf') def read(dtype=int): return list(map(dtype, input().split())) t = int(input()) def diff(a): return [a[1]-a[0], a[2]-a[1], a[0]-a[2]] n = 3 for _ in range(t): a = read() ans = inf for i in range(3): x = (i-1) % n y = (i+1) % n c = min(a[x], a[y]) v = (max(a[y], a[x]) - c) // 3 if (max(a[y], a[x]) - c) % 3 == 0 and a[i] + c >= v: ans = min(ans, c + v*3) print(-1 if ans == inf else ans) from math import gcd import sys input = sys.stdin.readline inf = float('inf') def read(dtype=int): return list(map(dtype, input().split())) t = int(input()) def diff(a): return [a[1]-a[0], a[2]-a[1], a[0]-a[2]] n = 3 for _ in range(t): a = read() ans = inf for i in range(3): x = (i-1) % n y = (i+1) % n c = min(a[x], a[y]) v = (max(a[y], a[x]) - c) // 3 if (max(a[y], a[x]) - c) % 3 == 0: ans = min(ans, c + v*3) print(-1 if ans == inf else ans)
ConDefects/ConDefects/Code/arc128_b/Python/40706832
condefects-python_data_2519
n = int(input()) for i in range(n): l = list(map(int,input().split())) if len(set(l)) <= 2: if l.count(l[0]) != 1: print(l[0]) elif l.count(l[1]) != 1: print(l[1]) else: lm = [min(l[0],l[1]),min(l[0],l[2]),min(l[2],l[1])] ls = [abs(l[0]-l[1]),abs(l[0]-l[2]),abs(l[2]-l[1])] lp = [i%3 for i in ls] if 0 not in lp: print(-1) else: ans = [] for i in range(3): if lp[i] != 0: continue t = 2 - i if l[t] < ls[i]//3: continue ans.append(ls[i]+lm[i]) if ans == []: print(-1) else: print(min(ans)) n = int(input()) for i in range(n): l = list(map(int,input().split())) if len(set(l)) <= 2: if l.count(l[0]) != 1: print(l[0]) elif l.count(l[1]) != 1: print(l[1]) else: lm = [min(l[0],l[1]),min(l[0],l[2]),min(l[2],l[1])] ls = [abs(l[0]-l[1]),abs(l[0]-l[2]),abs(l[2]-l[1])] lp = [i%3 for i in ls] if 0 not in lp: print(-1) else: ans = [] for i in range(3): if lp[i] != 0: continue t = 2 - i ans.append(ls[i]+lm[i]) if ans == []: print(-1) else: print(min(ans))
ConDefects/ConDefects/Code/arc128_b/Python/40552495
condefects-python_data_2520
T = int(input()) def calc(a,b,c): a,b = max(a,b), min(a,b) if a == b: # 成功 return a elif (a - b) % 3 == 0 and (a-b)//3 <= c: return a else: return -1 for _ in range(T): R, G, B = [int(x) for x in input().split()] l = [ calc(R,G,B), calc(R,B,G), calc(G,B,R), ] if len([x for x in l if x > -1]): print(min([x for x in l if x > -1])) else: print(-1) T = int(input()) def calc(a,b,c): a,b = max(a,b), min(a,b) if a == b: # 成功 return a elif (a - b) % 3 == 0: return a else: return -1 for _ in range(T): R, G, B = [int(x) for x in input().split()] l = [ calc(R,G,B), calc(R,B,G), calc(G,B,R), ] if len([x for x in l if x > -1]): print(min([x for x in l if x > -1])) else: print(-1)
ConDefects/ConDefects/Code/arc128_b/Python/37620333
condefects-python_data_2521
import bisect from collections import deque def solveLIS(lst): if lst == []: return 0 LIS = [lst[0]] ex = [] for i in range(len(lst)): if lst[i] > LIS[-1]: ex.append(len(LIS)) LIS.append(lst[i]) else: x = bisect.bisect_left(LIS,lst[i]) LIS[x] = lst[i] ex.append(x) return LIS, ex N = int(input()) A = list(map(int,input().split())) LIS, ex = solveLIS(A) LIS_size = len(LIS) size = [deque() for _ in range(N)] for i in range(N): size[ex[i]].append(i) def can_extend(A,N,LIS,size): LIS_rev = [-A[-1]] for i in reversed(range(N)): if -A[i] > LIS_rev[-1]: x = len(LIS_rev) LIS_rev.append(-A[i]) else: x = bisect.bisect_left(LIS_rev,-A[i]) LIS_rev[x] = -A[i] while x > 0 and size[LIS_size - x - 2]: j = size[LIS_size - x - 2].pop() if i <= j+1: continue if A[j] < A[i]-1: return True else: size[LIS_size - x - 2].append(j) break if len(solveLIS(A[:-1] + [10**10])[0]) > len(LIS): return True if len(solveLIS([0] + A[1:])[0]) > len(LIS): return True return False if can_extend(A,N,LIS,size): print(LIS_size+1) else: print(LIS_size) import bisect from collections import deque def solveLIS(lst): if lst == []: return 0 LIS = [lst[0]] ex = [] for i in range(len(lst)): if lst[i] > LIS[-1]: ex.append(len(LIS)) LIS.append(lst[i]) else: x = bisect.bisect_left(LIS,lst[i]) LIS[x] = lst[i] ex.append(x) return LIS, ex N = int(input()) A = list(map(int,input().split())) LIS, ex = solveLIS(A) LIS_size = len(LIS) size = [deque() for _ in range(N)] for i in range(N): size[ex[i]].append(i) def can_extend(A,N,LIS,size): LIS_rev = [-A[-1]] for i in reversed(range(N)): if -A[i] > LIS_rev[-1]: x = len(LIS_rev) LIS_rev.append(-A[i]) else: x = bisect.bisect_left(LIS_rev,-A[i]) LIS_rev[x] = -A[i] while LIS_size - x > 1 and size[LIS_size - x - 2]: j = size[LIS_size - x - 2].pop() if i <= j+1: continue if A[j] < A[i]-1: return True else: size[LIS_size - x - 2].append(j) break if len(solveLIS(A[:-1] + [10**10])[0]) > len(LIS): return True if len(solveLIS([0] + A[1:])[0]) > len(LIS): return True return False if can_extend(A,N,LIS,size): print(LIS_size+1) else: print(LIS_size)
ConDefects/ConDefects/Code/abc360_g/Python/55104573
condefects-python_data_2522
from bisect import* B=bisect_left N,*A=map(int,open(0).read().split()) o=[1]*N F=1<<60 A=A+[-F] for k in[-1,1]: d=[F]*N for i in range(N):o[i]+=B(d,A[i+k]-k);d[B(d,A[i])]=A[i] o=o[::-1];A=[-e for e in A][~0:0:-1];A+=F, print(max(o)) from bisect import* B=bisect_left N,*A=map(int,open(0).read().split()) o=[1]*N F=1<<60 A=A+[-F] for k in[-1,1]: d=[F]*N for i in range(N):o[i]+=B(d,A[i+k]-k);d[B(d,A[i])]=A[i] o=o[::-1];A=[-e for e in A][::-1][1:];A+=F, print(max(o))
ConDefects/ConDefects/Code/abc360_g/Python/55136355
condefects-python_data_2523
from atcoder.segtree import SegTree n = int(input()) alist = list(map(int, input().split())) se = set([0]) uplim = pow(10,9) se.add(uplim) for a in alist: se.add(a) # if a < uplim: se.add(a+1) # if a > 1: # se.add(a-1) so = sorted(se) dic = {v:i for i,v in enumerate(so)} zatu = [dic[a] for a in alist] def op(a,b): if a >= b: return a else: return b e = -10 seg0 = SegTree(op,e,[0 for i in range(len(so)+10)]) seg1 = SegTree(op,e,[0 for i in range(len(so)+10)]) # print(zatu) cj = 0 cx = 1 for i in range(n): a = zatu[i] now0 = seg0.prod(0,a) now1 = seg1.prod(0,a) seg0.set(a, max(now0+1, seg0.get(a))) seg1.set(a, max(now1+1, seg1.get(a))) seg1.set(cj, cx) cj = a+1 cx = now0+2 ans = seg1.all_prod() print(ans) from atcoder.segtree import SegTree n = int(input()) alist = list(map(int, input().split())) se = set([0]) uplim = pow(10,9) se.add(uplim) for a in alist: se.add(a) # if a < uplim: se.add(a+1) # if a > 1: # se.add(a-1) so = sorted(se) dic = {v:i for i,v in enumerate(so)} zatu = [dic[a] for a in alist] def op(a,b): if a >= b: return a else: return b e = -10 seg0 = SegTree(op,e,[0 for i in range(len(so)+10)]) seg1 = SegTree(op,e,[0 for i in range(len(so)+10)]) # print(zatu) cj = 0 cx = 1 for i in range(n): a = zatu[i] now0 = seg0.prod(0,a) now1 = seg1.prod(0,a) seg0.set(a, max(now0+1, seg0.get(a))) seg1.set(a, max(now1+1, seg1.get(a))) seg1.set(cj, max(cx, seg1.get(cj))) cj = a+1 cx = now0+2 ans = seg1.all_prod() print(ans)
ConDefects/ConDefects/Code/abc360_g/Python/55112153
condefects-python_data_2524
import sys readline = sys.stdin.readline #n = int(readline()) #*a, = map(int,readline().split()) # b = [list(map(int,readline().split())) for _ in range()] n = int(readline()) *a, = map(int,readline().split()) """ dp[i] = a[i] の左隣に仕切りを入れたときの積の和 q に保持する情報: (val, dp[prev]) """ MOD = 998244353 qM = [] qm = [] m = M = 0 dp = [0]*(n+1) dp[-1] = 1 for i in range(n)[::-1]: c = dp[i+1] while qM and qM[-1][0] <= a[i]: v,x = qM.pop() c += x M += (a[i]-v)*x M %= MOD c %= MOD qM.append((a[i], c)) M += a[i]*dp[i+1]%MOD dp[i] += M c = dp[i+1] while qm and qm[-1][0] >= a[i]: v,x = qm.pop() c += x m -= (v - a[i])*x m %= MOD c %= MOD qm.append((a[i], c)) m += a[i]*dp[i+1]%MOD dp[i] -= m dp[i] %= MOD print(dp[-1]) import sys readline = sys.stdin.readline #n = int(readline()) #*a, = map(int,readline().split()) # b = [list(map(int,readline().split())) for _ in range()] n = int(readline()) *a, = map(int,readline().split()) """ dp[i] = a[i] の左隣に仕切りを入れたときの積の和 q に保持する情報: (val, dp[prev]) """ MOD = 998244353 qM = [] qm = [] m = M = 0 dp = [0]*(n+1) dp[-1] = 1 for i in range(n)[::-1]: c = dp[i+1] while qM and qM[-1][0] <= a[i]: v,x = qM.pop() c += x M += (a[i]-v)*x M %= MOD c %= MOD qM.append((a[i], c)) M += a[i]*dp[i+1]%MOD dp[i] += M c = dp[i+1] while qm and qm[-1][0] >= a[i]: v,x = qm.pop() c += x m -= (v - a[i])*x m %= MOD c %= MOD qm.append((a[i], c)) m += a[i]*dp[i+1]%MOD dp[i] -= m dp[i] %= MOD print(dp[0])
ConDefects/ConDefects/Code/abc234_g/Python/43173883
condefects-python_data_2525
t=int(input()) for i in range(t): n=int(input()) s=list(map(str,input())) cnt=0 adj=0 for i in range(n): if(s[i]=='1'): cnt+=1 if(s[i-1]=='1'): adj=1 else: adj=0 if(cnt%2==1): print(-1) else: if(cnt==2 and adj==1): if(n==2 or n==3): print(-1) else: print(2) else: print(cnt//2) t=int(input()) for i in range(t): n=int(input()) s=list(map(str,input())) cnt=0 adj=0 for i in range(n): if(s[i]=='1'): cnt+=1 if(s[i-1]=='1'): adj=1 else: adj=0 if(cnt%2==1): print(-1) else: if(cnt==2 and adj==1): if(n==2 or n==3): print(-1) elif(n==4 and s[0]=='0' and s[3]=='0'): print(3) else: print(2) else: print(cnt//2)
ConDefects/ConDefects/Code/arc156_a/Python/45004259
condefects-python_data_2526
import sys # from collections import deque input = sys.stdin.readline # sys.setrecursionlimit(10**6) ############ ---- Input Functions ---- ############ def inp(): return int(input()) def inlt(): return list(map(int, input().split())) def insr(): s = input() return list(s[: len(s) - 1]) def invr(): return map(int, input().split()) for _ in range(inp()): n=inp() s=insr() if s.count("1")%2 or s=="011" or s=='110': print(-1) continue if s=='0110': print(3) continue if s.count('1')==2 and s.count('11')==1: print(2) continue print(s.count('1')//2) import sys # from collections import deque input = sys.stdin.readline # sys.setrecursionlimit(10**6) ############ ---- Input Functions ---- ############ def inp(): return int(input()) def inlt(): return list(map(int, input().split())) def insr(): s = input() return list(s[: len(s) - 1]) def invr(): return map(int, input().split()) for _ in range(inp()): n=inp() s=insr() s="".join(s) # print(s) if s.count("1")%2 or s=="011" or s=='110': print(-1) continue if s=='0110': print(3) continue if s.count('1')==2 and s.count('11')==1: print(2) continue print(s.count('1')//2)
ConDefects/ConDefects/Code/arc156_a/Python/45086330
condefects-python_data_2527
t=int(input()) for _ in range(t): n=int(input()) s=input() L=[] p=[] w2=0 no_w2=0 num_1=0 for i in range(n): if s[i]=="1": p.append(1) num_1+=1 else: if len(p)==2: L.append(p) p=[] w2+=1 if len(p)!=0: L.append(p) p=[] no_w2+=1 if i==n-1: if len(p)==2: L.append(p) p=[] w2+=1 if len(p)!=0: L.append(p) p=[] no_w2+=1 if num_1%2==1: print(-1) elif s=="011": print(-1) elif s=="110": print(-1) elif s=="0110": print(3) elif len(L)==0: print(0) elif w2==1: print(num_1//2+1) else: print(num_1//2) t=int(input()) for _ in range(t): n=int(input()) s=input() L=[] p=[] w2=0 no_w2=0 num_1=0 for i in range(n): if s[i]=="1": p.append(1) num_1+=1 else: if len(p)==2: L.append(p) p=[] w2+=1 if len(p)!=0: L.append(p) p=[] no_w2+=1 if i==n-1: if len(p)==2: L.append(p) p=[] w2+=1 if len(p)!=0: L.append(p) p=[] no_w2+=1 if num_1%2==1: print(-1) elif s=="011": print(-1) elif s=="110": print(-1) elif s=="0110": print(3) elif len(L)==0: print(0) elif w2==1 and no_w2==0: print(num_1//2+1) else: print(num_1//2)
ConDefects/ConDefects/Code/arc156_a/Python/43775294
condefects-python_data_2528
#コーディングはこのセルで from collections import deque,defaultdict from fractions import Fraction from itertools import permutations from functools import cmp_to_key import math,sys,heapq,random,bisect,copy def LMI() : return list(map(int,input().split())) def LMS() : return list(map(str,input().split())) def MI() : return map(int,input().split()) def LLI(N) : return [LMI() for _ in range(N)] def LLS(N): return [LMS() for _ in range(N)] def LS(N) : return [input() for _ in range(N)] def LI(N) : return [int(input()) for _ in range(N)] def II() : return int(input()) #入力 T=II() for _ in range(T): N=II() S=input() count=0 for i in range(N): if S[i]=='1': count+=1 if count%2==1: print(-1) else: if count!=2: print(count//2) else: flg=0 for i in range(N-1): if S[i]=='1' and S[i+1]=='1': flg=1 if flg: if N==3: print(-1) elif N==4: if S=='0110': print(3) else: print(3) else: print(2) else: print(1) #コーディングはこのセルで from collections import deque,defaultdict from fractions import Fraction from itertools import permutations from functools import cmp_to_key import math,sys,heapq,random,bisect,copy def LMI() : return list(map(int,input().split())) def LMS() : return list(map(str,input().split())) def MI() : return map(int,input().split()) def LLI(N) : return [LMI() for _ in range(N)] def LLS(N): return [LMS() for _ in range(N)] def LS(N) : return [input() for _ in range(N)] def LI(N) : return [int(input()) for _ in range(N)] def II() : return int(input()) #入力 T=II() for _ in range(T): N=II() S=input() count=0 for i in range(N): if S[i]=='1': count+=1 if count%2==1: print(-1) else: if count!=2: print(count//2) else: flg=0 for i in range(N-1): if S[i]=='1' and S[i+1]=='1': flg=1 if flg: if N==3: print(-1) elif N==4: if S=='0110': print(3) else: print(2) else: print(2) else: print(1)
ConDefects/ConDefects/Code/arc156_a/Python/44009597
condefects-python_data_2529
n, k = map(int, input().split()) a = list(map(int, input().split())) for i in range(n): if a[i]%k==0: print(a[i]/k, end=" ") n, k = map(int, input().split()) a = list(map(int, input().split())) for i in range(n): if a[i]%k==0: print(int(a[i]/k), end=" ")
ConDefects/ConDefects/Code/abc347_a/Python/54752692
condefects-python_data_2530
N,K = map(int,input().split()) A = list(map(int,input().split())) for i in range(N): if A[i]%K == 0: print(A[i]/K) N,K = map(int,input().split()) A = list(map(int,input().split())) for i in range(N): if A[i]%K == 0: print(A[i]//K,end=" ")
ConDefects/ConDefects/Code/abc347_a/Python/55038235
condefects-python_data_2531
n, k = list(map(int, input().split())) a = list(map(int, input().split())) b = [] for i in range(n): if a[i] % k == 0: c = a[i] / k b.append(c) sorted_b = sorted(b) print(" ".join(map(str, sorted_b))) n, k = list(map(int, input().split())) a = list(map(int, input().split())) b = [] for i in range(n): if a[i] % k == 0: c = a[i] // k b.append(c) sorted_b = sorted(b) print(" ".join(map(str, sorted_b)))
ConDefects/ConDefects/Code/abc347_a/Python/54976417
condefects-python_data_2532
N,K = map(int,input().split()) A = list(map(int,input().split())) B = list() for i in A: if i%K==0: B.append(i//K) B.sort() for i in B: print(i,end="") N,K = map(int,input().split()) A = list(map(int,input().split())) B = list() for i in A: if i%K==0: B.append(i//K) B.sort() for i in B: print(i,end=" ")
ConDefects/ConDefects/Code/abc347_a/Python/54997243
condefects-python_data_2533
n, k = map(int, input().split()) a = list(map(int, input().split())) ans = [] for i in range(n): if a[i] % k == 0: ans.append(a[i]//2) print(*ans) n, k = map(int, input().split()) a = list(map(int, input().split())) ans = [] for i in range(n): if a[i] % k == 0: ans.append(a[i]//k) print(*ans)
ConDefects/ConDefects/Code/abc347_a/Python/54768582
condefects-python_data_2534
n, k = map(int, input().split()) a = list(map(int, input().split())) b = [] for i in range(n): if a[i] % k == 0: b.append(a[i] / k) b.sort() print(*b) n, k = map(int, input().split()) a = list(map(int, input().split())) b = [] for i in range(n): if a[i] % k == 0: b.append(a[i]//k) b.sort() print(*b)
ConDefects/ConDefects/Code/abc347_a/Python/54735895
condefects-python_data_2535
n,m=map(int,input().split()) A=list(map(int,input().split())) li=list(sorted(A[2:])) ans=10**18 for i in range(2,n-m+1): ans=min(ans,max(0,A[0]-A[i])+max(0,A[i+m-1]-A[1])) print(ans) n,m=map(int,input().split()) A=list(map(int,input().split())) li=list(sorted(A[2:])) ans=10**18 for i in range(2,n-m+1): ans=min(ans,max(0,A[0]-li[i-2])+max(0,li[i+m-3]-A[1])) print(ans)
ConDefects/ConDefects/Code/arc163_b/Python/44451318
condefects-python_data_2536
#from collections import defaultdict #d = defaultdict(int) #from collections import deque #import math #import heapq #from queue import Queue #import numpy as np #Mo=998244353 #t=input() #n=int(input()) #l,r = list(input().split()) n,m=list(map(int, input().split())) A = list(map(int, input().split())) #a= [int(input()) for _ in range(n)] an=10000000000000 amin = A[0] amax = A[1] B = [] for i in range(2,n): B.append(A[i]) B.sort() for i in range(n-2-m): val = max(amin-B[i],0)+max(B[i+m-1]-amax,0) if an >val: an=val print(an) #print(1) if a+n <= m else print(0) #print(' '.join(map(str,d))) #print('Yes') if b else print('No') #print('YES') if b else print('NO') #from collections import defaultdict #d = defaultdict(int) #from collections import deque #import math #import heapq #from queue import Queue #import numpy as np #Mo=998244353 #t=input() #n=int(input()) #l,r = list(input().split()) n,m=list(map(int, input().split())) A = list(map(int, input().split())) #a= [int(input()) for _ in range(n)] an=10000000000000 amin = A[0] amax = A[1] B = [] for i in range(2,n): B.append(A[i]) B.sort() for i in range(n-2-m+1): val = max(amin-B[i],0)+max(B[i+m-1]-amax,0) if an >val: an=val print(an) #print(1) if a+n <= m else print(0) #print(' '.join(map(str,d))) #print('Yes') if b else print('No') #print('YES') if b else print('NO')
ConDefects/ConDefects/Code/arc163_b/Python/43944210
condefects-python_data_2537
import sys def favorite_game(N, M, A): lower_start, upper_start = min(A[0], A[1]), max(A[0], A[1]) B = sorted(A[2:]) min_move = float("inf") for left in range(len(B) - M + 1): right = left + M - 1 lower = B[left] upper = B[right] move = 0 if lower < lower_start: move += lower_start - lower if upper_start < upper: move += upper - upper_start min_move = min(min_move, move) return min_move def resolve(): N, M = [int(e) for e in sys.stdin.readline().split()] A = [int(e) for e in sys.stdin.readline().split()] print(favorite_game(N, M, A)) resolve() import sys def favorite_game(N, M, A): lower_start, upper_start = A[0], A[1] B = sorted(A[2:]) min_move = float("inf") for left in range(len(B) - M + 1): right = left + M - 1 lower = B[left] upper = B[right] move = 0 if lower < lower_start: move += lower_start - lower if upper_start < upper: move += upper - upper_start min_move = min(min_move, move) return min_move def resolve(): N, M = [int(e) for e in sys.stdin.readline().split()] A = [int(e) for e in sys.stdin.readline().split()] print(favorite_game(N, M, A)) resolve()
ConDefects/ConDefects/Code/arc163_b/Python/43716281
condefects-python_data_2538
n, m = map(int, input().split()) a1, a2, *a = list(map(int, input().split())) a.sort() ans = 10**20 for i in range(n-2): if i+m-1 > n-3: break pre = max((a1 - a[0]), 0) + max(a[i+m-1] - a2, 0) ans = min(ans, pre) print(ans) n, m = map(int, input().split()) a1, a2, *a = list(map(int, input().split())) a.sort() ans = 10**20 for i in range(n-2): if i+m-1 > n-3: break pre = max((a1 - a[i]), 0) + max(a[i+m-1] - a2, 0) ans = min(ans, pre) print(ans)
ConDefects/ConDefects/Code/arc163_b/Python/45704677
condefects-python_data_2539
ROOT = 3 MOD = 998244353 roots = [pow(ROOT,(MOD-1)>>i,MOD) for i in range(24)] # 1 の 2^i 乗根 iroots = [pow(x,MOD-2,MOD) for x in roots] # 1 の 2^i 乗根の逆元 def untt(a,n): for i in range(n): m = 1<<(n-i-1) for s in range(1<<i): w_N = 1 s *= m*2 for p in range(m): a[s+p], a[s+p+m] = (a[s+p]+a[s+p+m])%MOD, (a[s+p]-a[s+p+m])*w_N%MOD w_N = w_N*roots[n-i]%MOD def iuntt(a,n): for i in range(n): m = 1<<i for s in range(1<<(n-i-1)): w_N = 1 s *= m*2 for p in range(m): a[s+p], a[s+p+m] = (a[s+p]+a[s+p+m]*w_N)%MOD, (a[s+p]-a[s+p+m]*w_N)%MOD w_N = w_N*iroots[i+1]%MOD inv = pow((MOD+1)//2,n,MOD) for i in range(1<<n): a[i] = a[i]*inv%MOD def convolution(a,b): la = len(a) lb = len(b) if min(la, lb) <= 50: if la < lb: la,lb = lb,la a,b = b,a res = [0]*(la+lb-1) for i in range(la): for j in range(lb): res[i+j] += a[i]*b[j] res[i+j] %= MOD return res a = a[:]; b = b[:] deg = la+lb-2 n = deg.bit_length() N = 1<<n a += [0]*(N-len(a)) b += [0]*(N-len(b)) untt(a,n) untt(b,n) for i in range(N): a[i] = a[i]*b[i]%MOD iuntt(a,n) return a[:deg+1] SIZE = 2*10**5 inv = [0]*SIZE # inv[j] = j^{-1} mod MOD fac = [0]*SIZE # fac[j] = j! mod MOD finv = [0]*SIZE # finv[j] = (j!)^{-1} mod MOD fac[0] = fac[1] = 1 finv[0] = finv[1] = 1 for i in range(2,SIZE): fac[i] = fac[i-1]*i%MOD finv[-1] = pow(fac[-1],MOD-2,MOD) for i in range(SIZE-1,0,-1): finv[i-1] = finv[i]*i%MOD inv[i] = finv[i]*fac[i-1]%MOD def choose(n,r): # nCk mod MOD の計算 if 0 <= r <= n: return (fac[n]*finv[r]%MOD)*finv[n-r]%MOD else: return 0 import sys readline = sys.stdin.readline #n = int(readline()) #*a, = map(int,readline().split()) # b = [list(map(int,readline().split())) for _ in range()] """ f_n: n で一致 g_n: n で 0 -> 0 h_n: n で初めて一致 g(x)h(x) = f(x) から h を求める """ *abc,T = map(int,readline().split()) a,b,c = sorted(abc) inv2 = (MOD+1)//2 INV2 = [1] for i in range(3*T+1): INV2.append(INV2[-1]*inv2%MOD) finv += [0]*(2*T) def get(T,v1,v2): f = [finv[k]*finv[k+v1]%MOD*finv[k+v2]%MOD for k in range(T+1)] g = [finv[k]*finv[k-v1]%MOD*finv[k-v2]%MOD for k in range(T+1)] h = convolution(f,g)[:T+1] for i in range(T+1): h[i] *= INV2[3*i]*pow(fac[i],3,MOD)%MOD h[i] %= MOD return h v1,v2 = (b-a)//2,(c-a)//2 f = get(T,v1,v2) g = get(T,0,0) #print(f,g) def fpsdiv(f,g,N): assert g[0] != 0 lg = len(g) if g[0] != 1: a = pow(g[0],MOD-2,MOD) for i in range(len(f)): f[i] = f[i]*a%MOD for i in range(lg): g[i] = g[i]*a%MOD f += [0]*max(0,N+1-len(f)) for i in range(N+1): for j in range(1,min(i+1,lg)): f[i] = (f[i] - g[j]*f[i-j])%MOD return f polymul = convolution def fpsinv(f,N): g = [pow(f[0],MOD-2,MOD)] n = 1 while n <= N: ng = [2*i for i in g]+[0]*n fgg = polymul(polymul(g,g),f) for i in range(min(len(fgg),2*n)): ng[i] -= fgg[i] ng[i] %= MOD n *= 2 g = ng return g[:N+1] ginv = fpsinv(g,T+1) ans = 0 for i in range(T+1): ans += f[i]*ginv[T-i] ans %= MOD print(ans) ROOT = 3 MOD = 998244353 roots = [pow(ROOT,(MOD-1)>>i,MOD) for i in range(24)] # 1 の 2^i 乗根 iroots = [pow(x,MOD-2,MOD) for x in roots] # 1 の 2^i 乗根の逆元 def untt(a,n): for i in range(n): m = 1<<(n-i-1) for s in range(1<<i): w_N = 1 s *= m*2 for p in range(m): a[s+p], a[s+p+m] = (a[s+p]+a[s+p+m])%MOD, (a[s+p]-a[s+p+m])*w_N%MOD w_N = w_N*roots[n-i]%MOD def iuntt(a,n): for i in range(n): m = 1<<i for s in range(1<<(n-i-1)): w_N = 1 s *= m*2 for p in range(m): a[s+p], a[s+p+m] = (a[s+p]+a[s+p+m]*w_N)%MOD, (a[s+p]-a[s+p+m]*w_N)%MOD w_N = w_N*iroots[i+1]%MOD inv = pow((MOD+1)//2,n,MOD) for i in range(1<<n): a[i] = a[i]*inv%MOD def convolution(a,b): la = len(a) lb = len(b) if min(la, lb) <= 50: if la < lb: la,lb = lb,la a,b = b,a res = [0]*(la+lb-1) for i in range(la): for j in range(lb): res[i+j] += a[i]*b[j] res[i+j] %= MOD return res a = a[:]; b = b[:] deg = la+lb-2 n = deg.bit_length() N = 1<<n a += [0]*(N-len(a)) b += [0]*(N-len(b)) untt(a,n) untt(b,n) for i in range(N): a[i] = a[i]*b[i]%MOD iuntt(a,n) return a[:deg+1] SIZE = 2*10**5 inv = [0]*SIZE # inv[j] = j^{-1} mod MOD fac = [0]*SIZE # fac[j] = j! mod MOD finv = [0]*SIZE # finv[j] = (j!)^{-1} mod MOD fac[0] = fac[1] = 1 finv[0] = finv[1] = 1 for i in range(2,SIZE): fac[i] = fac[i-1]*i%MOD finv[-1] = pow(fac[-1],MOD-2,MOD) for i in range(SIZE-1,0,-1): finv[i-1] = finv[i]*i%MOD inv[i] = finv[i]*fac[i-1]%MOD def choose(n,r): # nCk mod MOD の計算 if 0 <= r <= n: return (fac[n]*finv[r]%MOD)*finv[n-r]%MOD else: return 0 import sys readline = sys.stdin.readline #n = int(readline()) #*a, = map(int,readline().split()) # b = [list(map(int,readline().split())) for _ in range()] """ f_n: n で一致 g_n: n で 0 -> 0 h_n: n で初めて一致 g(x)h(x) = f(x) から h を求める """ *abc,T = map(int,readline().split()) a,b,c = sorted(abc) inv2 = (MOD+1)//2 INV2 = [1] for i in range(3*T+1): INV2.append(INV2[-1]*inv2%MOD) finv += [0]*(2*10**5) def get(T,v1,v2): f = [finv[k]*finv[k+v1]%MOD*finv[k+v2]%MOD for k in range(T+1)] g = [finv[k]*finv[k-v1]%MOD*finv[k-v2]%MOD for k in range(T+1)] h = convolution(f,g)[:T+1] for i in range(T+1): h[i] *= INV2[3*i]*pow(fac[i],3,MOD)%MOD h[i] %= MOD return h v1,v2 = (b-a)//2,(c-a)//2 f = get(T,v1,v2) g = get(T,0,0) #print(f,g) def fpsdiv(f,g,N): assert g[0] != 0 lg = len(g) if g[0] != 1: a = pow(g[0],MOD-2,MOD) for i in range(len(f)): f[i] = f[i]*a%MOD for i in range(lg): g[i] = g[i]*a%MOD f += [0]*max(0,N+1-len(f)) for i in range(N+1): for j in range(1,min(i+1,lg)): f[i] = (f[i] - g[j]*f[i-j])%MOD return f polymul = convolution def fpsinv(f,N): g = [pow(f[0],MOD-2,MOD)] n = 1 while n <= N: ng = [2*i for i in g]+[0]*n fgg = polymul(polymul(g,g),f) for i in range(min(len(fgg),2*n)): ng[i] -= fgg[i] ng[i] %= MOD n *= 2 g = ng return g[:N+1] ginv = fpsinv(g,T+1) ans = 0 for i in range(T+1): ans += f[i]*ginv[T-i] ans %= MOD print(ans)
ConDefects/ConDefects/Code/abc289_h/Python/43246591
condefects-python_data_2540
from atcoder.scc import* N,*A=map(int,open(0).read().split()) G=SCCGraph(N) for i in range(N): G.add_edge(i,A[i]-1) d=[0]*N for g in G.scc()[::-1]: for v in g:d[v]=len(g)*-~d[A[g[0]]-1] print(sum(d)) from atcoder.scc import* N,*A=map(int,open(0).read().split()) G=SCCGraph(N) for i in range(N): G.add_edge(i,A[i]-1) d=[0]*N for g in G.scc()[::-1]: for v in g:d[v]=len(g)if len(g)>1else d[A[g[0]]-1]+1 print(sum(d))
ConDefects/ConDefects/Code/abc357_e/Python/54953956
condefects-python_data_2541
#!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n, m = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) orientation = [None] * m graph = [[] for _ in range(n)] for i in range(m): graph[a[i] - 1].append((b[i] - 1, i)) graph[b[i] - 1].append((a[i] - 1, i)) dist = [-1] * n parent = [None] * n parentEdge = [None] * n for i in range(n): if dist[i] != -1: continue stack = [i] vertices = [] dist[i] = 0 while stack: v = stack.pop() if dist[v] != -1 and v != i: continue vertices.append(v) if parentEdge[v] is not None: orientation[parentEdge[v]] = (parent[v], v) dist[v] = dist[parent[v]] + 1 for u, index in graph[v]: if parent[v] == u: continue if dist[v] != -1: stack.append(u) parent[u] = v parentEdge[u] = index for v in vertices: for u, index in graph[v]: if orientation[index] is not None: continue orientation[index] = (u, v) if dist[u] > dist[v] else (v, u) ans = [] for i in range(m): if orientation[i][0] == a[i]: ans.append("0") else: ans.append("1") print("".join(ans)) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._file = 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): 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): 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): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n, m = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) orientation = [None] * m graph = [[] for _ in range(n)] for i in range(m): graph[a[i] - 1].append((b[i] - 1, i)) graph[b[i] - 1].append((a[i] - 1, i)) dist = [-1] * n parent = [None] * n parentEdge = [None] * n for i in range(n): if dist[i] != -1: continue stack = [i] vertices = [] dist[i] = 0 while stack: v = stack.pop() if dist[v] != -1 and v != i: continue vertices.append(v) if parentEdge[v] is not None: orientation[parentEdge[v]] = (parent[v], v) dist[v] = dist[parent[v]] + 1 for u, index in graph[v]: if parent[v] == u: continue if dist[v] != -1: stack.append(u) parent[u] = v parentEdge[u] = index for v in vertices: for u, index in graph[v]: if orientation[index] is not None: continue orientation[index] = (u, v) if dist[u] > dist[v] else (v, u) ans = [] for i in range(m): if orientation[i][0] == a[i] - 1: ans.append("0") else: ans.append("1") print("".join(ans)) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._file = 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): 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): 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): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main()
ConDefects/ConDefects/Code/arc143_d/Python/32778317
condefects-python_data_2542
import sys readline = sys.stdin.readline #n = int(readline()) n,m = map(int,readline().split()) *a, = map(lambda x:int(x)-1,readline().split()) *b, = map(lambda x:int(x)-1,readline().split()) g = [[] for _ in range(n)] for i in range(m): ai = a[i] bi = b[i] g[ai].append((bi,i)) g[bi].append((ai,i)) def dfs(i): st = [(i,-1)] while st: #print(st) v,idx = st.pop() #print(v,idx) if used[v]: #print(idx) if a[idx] == v: ans[idx] = 1 continue if b[idx] == v: ans[idx] = 1 used[v] = 1 for c,idx in g[v]: if used[c] == 0: st.append((c,idx)) parent[c] = v ans = [0]*m used = [0]*n parent = [0]*n for i in range(n): if used[i]: continue dfs(i) r = "".join(map(str,ans)) print(r) import sys readline = sys.stdin.readline #n = int(readline()) n,m = map(int,readline().split()) *a, = map(lambda x:int(x)-1,readline().split()) *b, = map(lambda x:int(x)-1,readline().split()) g = [[] for _ in range(n)] for i in range(m): ai = a[i] bi = b[i] g[ai].append((bi,i)) g[bi].append((ai,i)) def dfs(i): st = [(i,-1)] while st: #print(st) v,idx = st.pop() #print(v,idx) if used[v]: #print(idx) if a[idx] == v: ans[idx] = 1 continue if idx != -1 and b[idx] == v: ans[idx] = 1 used[v] = 1 for c,idx in g[v]: if used[c] == 0: st.append((c,idx)) parent[c] = v ans = [0]*m used = [0]*n parent = [0]*n for i in range(n): if used[i]: continue dfs(i) r = "".join(map(str,ans)) print(r)
ConDefects/ConDefects/Code/arc143_d/Python/32782351
condefects-python_data_2543
import bisect import copy import decimal import fractions import heapq import itertools import math import random import sys import time from collections import Counter,deque,defaultdict from functools import lru_cache,reduce from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max def _heappush_max(heap,item): heap.append(item) heapq._siftdown_max(heap, 0, len(heap)-1) def _heappushpop_max(heap, item): if heap and item < heap[0]: item, heap[0] = heap[0], item heapq._siftup_max(heap, 0) return item from math import gcd as GCD read=sys.stdin.read readline=sys.stdin.readline readlines=sys.stdin.readlines import heapq import random from collections import defaultdict,deque class Graph: def __init__(self,V,edges=False,graph=False,directed=False,weighted=False,inf=float("inf")): self.V=V self.directed=directed self.weighted=weighted self.inf=inf if graph: self.graph=graph self.edges=[] for i in range(self.V): if self.weighted: for j,d in self.graph[i]: if self.directed or not self.directed and i<=j: self.edges.append((i,j,d)) else: for j in self.graph[i]: if self.directed or not self.directed and i<=j: self.edges.append((i,j)) else: self.edges=edges self.graph=[[] for i in range(self.V)] if weighted: for i,j,d in self.edges: self.graph[i].append((j,d)) if not self.directed: self.graph[j].append((i,d)) else: for i,j in self.edges: self.graph[i].append(j) if not self.directed: self.graph[j].append(i) def SIV_DFS(self,s,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,lowlink=False,parents=False,postorder=False,preorder=False,subtree_size=False,topological_sort=False,unweighted_dist=False,weighted_dist=False): seen=[False]*self.V finished=[False]*self.V if directed_acyclic or cycle_detection or topological_sort: dag=True if euler_tour: et=[] if linked_components: lc=[] if lowlink: order=[None]*self.V ll=[None]*self.V idx=0 if parents or cycle_detection or lowlink or subtree_size: ps=[None]*self.V if postorder or topological_sort: post=[] if preorder: pre=[] if subtree_size: ss=[1]*self.V if unweighted_dist or bipartite_graph: uwd=[self.inf]*self.V uwd[s]=0 if weighted_dist: wd=[self.inf]*self.V wd[s]=0 stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) if euler_tour: et.append(x) if linked_components: lc.append(x) if lowlink: order[x]=idx ll[x]=idx idx+=1 if preorder: pre.append(x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) if parents or cycle_detection or lowlink or subtree_size: ps[y]=x if unweighted_dist or bipartite_graph: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d elif not finished[y]: if (directed_acyclic or cycle_detection or topological_sort) and dag: dag=False if cycle_detection: cd=(y,x) elif not finished[x]: finished[x]=True if euler_tour: et.append(~x) if lowlink: bl=True for y in self.graph[x]: if self.weighted: y,d=y if ps[x]==y and bl: bl=False continue ll[x]=min(ll[x],order[y]) if x!=s: ll[ps[x]]=min(ll[ps[x]],ll[x]) if postorder or topological_sort: post.append(x) if subtree_size: for y in self.graph[x]: if self.weighted: y,d=y if y==ps[x]: continue ss[x]+=ss[y] if bipartite_graph: bg=[[],[]] for tpl in self.edges: x,y=tpl[:2] if self.weighted else tpl if uwd[x]==self.inf or uwd[y]==self.inf: continue if not uwd[x]%2^uwd[y]%2: bg=False break else: for x in range(self.V): if uwd[x]==self.inf: continue bg[uwd[x]%2].append(x) retu=() if bipartite_graph: retu+=(bg,) if cycle_detection: if dag: cd=[] else: y,x=cd cd=self.Route_Restoration(y,x,ps) retu+=(cd,) if directed_acyclic: retu+=(dag,) if euler_tour: retu+=(et,) if linked_components: retu+=(lc,) if lowlink: retu=(ll,) if parents: retu+=(ps,) if postorder: retu+=(post,) if preorder: retu+=(pre,) if subtree_size: retu+=(ss,) if topological_sort: if dag: tp_sort=post[::-1] else: tp_sort=[] retu+=(tp_sort,) if unweighted_dist: retu+=(uwd,) if weighted_dist: retu+=(wd,) if len(retu)==1: retu=retu[0] return retu def MIV_DFS(self,initial_vertices=None,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,lowlink=False,parents=False,postorder=False,preorder=False,subtree_size=False,topological_sort=False,unweighted_dist=False,weighted_dist=False): if initial_vertices==None: initial_vertices=[s for s in range(self.V)] seen=[False]*self.V finished=[False]*self.V if bipartite_graph: bg=[None]*self.V cnt=-1 if directed_acyclic or cycle_detection or topological_sort: dag=True if euler_tour: et=[] if linked_components: lc=[] if lowlink: order=[None]*self.V ll=[None]*self.V idx=0 if parents or cycle_detection or lowlink or subtree_size: ps=[None]*self.V if postorder or topological_sort: post=[] if preorder: pre=[] if subtree_size: ss=[1]*self.V if bipartite_graph or unweighted_dist: uwd=[self.inf]*self.V if weighted_dist: wd=[self.inf]*self.V for s in initial_vertices: if seen[s]: continue if bipartite_graph: cnt+=1 bg[s]=(cnt,0) if linked_components: lc.append([]) if bipartite_graph or unweighted_dist: uwd[s]=0 if weighted_dist: wd[s]=0 stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) if euler_tour: et.append(x) if linked_components: lc[-1].append(x) if lowlink: order[x]=idx ll[x]=idx idx+=1 if preorder: pre.append(x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) if bipartite_graph: bg[y]=(cnt,bg[x][1]^1) if parents or cycle_detection or lowlink or subtree_size: ps[y]=x if unweighted_dist or bipartite_graph: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d elif not finished[y]: if directed_acyclic and dag: dag=False if cycle_detection: cd=(y,x) elif not finished[x]: finished[x]=True if euler_tour: et.append(~x) if lowlink: bl=True for y in self.graph[x]: if self.weighted: y,d=y if ps[x]==y and bl: bl=False continue ll[x]=min(ll[x],order[y]) if x!=s: ll[ps[x]]=min(ll[ps[x]],ll[x]) if postorder or topological_sort: post.append(x) if subtree_size: for y in self.graph[x]: if self.weighted: y,d=y if y==ps[x]: continue ss[x]+=ss[y] if bipartite_graph: bg_=bg bg=[[[],[]] for i in range(cnt+1)] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if not bg_[i][1]^bg_[j][1]: bg[bg_[i][0]]=False for x in range(self.V): if bg[bg_[x][0]]: bg[bg_[x][0]][bg_[x][1]].append(x) retu=() if bipartite_graph: retu+=(bg,) if cycle_detection: if dag: cd=[] else: y,x=cd cd=self.Route_Restoration(y,x,ps) retu+=(cd,) if directed_acyclic: retu+=(dag,) if euler_tour: retu+=(et,) if linked_components: retu+=(lc,) if lowlink: retu=(ll,) if parents: retu+=(ps,) if postorder: retu+=(post,) if preorder: retu+=(pre,) if subtree_size: retu+=(ss,) if topological_sort: if dag: tp_sort=post[::-1] else: tp_sort=[] retu+=(tp_sort,) if unweighted_dist: retu+=(uwd,) if weighted_dist: retu+=(wd,) if len(retu)==1: retu=retu[0] return retu def SIV_BFS(self,s,bfs_tour=False,bipartite_graph=False,linked_components=False,parents=False,unweighted_dist=False,weighted_dist=False): seen=[False]*self.V seen[s]=True if bfs_tour: bt=[s] if linked_components: lc=[s] if parents: ps=[None]*self.V if unweighted_dist or bipartite_graph: uwd=[self.inf]*self.V uwd[s]=0 if weighted_dist: wd=[self.inf]*self.V wd[s]=0 queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) if bfs_tour: bt.append(y) if linked_components: lc.append(y) if parents: ps[y]=x if unweighted_dist or bipartite_graph: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d if bipartite_graph: bg=[[],[]] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if uwd[i]==self.inf or uwd[j]==self.inf: continue if not uwd[i]%2^uwd[j]%2: bg=False break else: for x in range(self.V): if uwd[x]==self.inf: continue bg[uwd[x]%2].append(x) retu=() if bfs_tour: retu+=(bt,) if bipartite_graph: retu+=(bg,) if linked_components: retu+=(lc,) if parents: retu+=(ps,) if unweighted_dist: retu+=(uwd,) if weighted_dist: retu+=(wd,) if len(retu)==1: retu=retu[0] return retu def MIV_BFS(self,initial_vertices=None,bipartite_graph=False,linked_components=False,parents=False,unweighted_dist=False,weighted_dist=False): if initial_vertices==None: initial_vertices=[i for i in range(self.V)] seen=[False]*self.V if bipartite_graph: bg=[None]*self.V cnt=-1 if linked_components: lc=[] if parents: ps=[None]*self.V if unweighted_dist: uwd=[self.inf]*self.V if weighted_dist: wd=[self.inf]*self.V for s in initial_vertices: if seen[s]: continue seen[s]=True if bipartite_graph: cnt+=1 bg[s]=(cnt,0) if linked_components: lc.append([s]) if unweighted_dist: uwd[s]=0 if weighted_dist: wd[s]=0 queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) if bipartite_graph: bg[y]=(cnt,bg[x][1]^1) if linked_components: lc[-1].append(y) if parents: ps[y]=x if unweighted_dist: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d if bipartite_graph: bg_=bg bg=[[[],[]] for i in range(cnt+1)] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if not bg_[i][1]^bg_[j][1]: bg[bg_[i][0]]=False for x in range(self.V): if bg[bg_[x][0]]: bg[bg_[x][0]][bg_[x][1]].append(x) retu=() if bipartite_graph: retu+=(bg,) if linked_components: retu+=(lc,) if parents: retu=(ps,) if unweighted_dist: retu+=(uwd,) if weighted_dist: retu+=(wd,) if len(retu)==1: retu=retu[0] return retu def Tree_Diameter(self,weighted=False): def Farthest_Point(u): dist=self.SIV_BFS(u,weighted_dist=True) if weighted else self.SIV_BFS(u,unweighted_dist=True) fp=0 for i in range(self.V): if dist[fp]<dist[i]: fp=i return fp,dist[fp] u,d=Farthest_Point(0) v,d=Farthest_Point(u) return u,v,d def SCC(self): reverse_graph=[[] for i in range(self.V)] for tpl in self.edges: u,v=tpl[:2] if self.weighted else tpl reverse_graph[v].append(u) postorder=self.MIV_DFS(postorder=True) scc_points=[] seen=[False]*self.V for s in postorder[::-1]: if seen[s]: continue queue=deque([s]) seen[s]=True lst=[] while queue: x=queue.popleft() lst.append(x) for y in reverse_graph[x]: if not seen[y]: seen[y]=True queue.append(y) scc_points.append(lst) l=len(scc_points) idx=[None]*self.V for i in range(l): for x in scc_points[i]: idx[x]=i scc_edges=set() for tpl in self.edges: u,v=tpl[:2] if self.weighted else tpl if idx[u]!=idx[v]: scc_edges.add((idx[u],idx[v])) scc_edges=list(scc_edges) return scc_points,scc_edges def Build_LCA(self,s,segment_tree=False): self.lca_segment_tree=segment_tree if self.lca_segment_tree: self.lca_euler_tour,self.lca_parents,depth=self.SIV_DFS(s,euler_tour=True,parents=True,unweighted_dist=True) self.lca_dfs_in_index=[None]*self.V self.lca_dfs_out_index=[None]*self.V for i,x in enumerate(self.lca_euler_tour): if x>=0: self.lca_dfs_in_index[x]=i else: self.lca_dfs_out_index[~x]=i self.ST=Segment_Tree(2*self.V,lambda x,y:min(x,y),self.V) lst=[None]*(2*self.V) for i in range(2*self.V-1): if self.lca_euler_tour[i]>=0: lst[i]=depth[self.lca_euler_tour[i]] else: lst[i]=depth[self.lca_parents[~self.lca_euler_tour[i]]] lst[2*self.V-1]=-1 self.ST.Build(lst) else: self.lca_parents,self.lca_depth=self.SIV_DFS(s,parents=True,unweighted_dist=True) self.lca_parents[s]=s self.lca_PD=Path_Doubling(self.V,self.lca_parents) self.lca_PD.Build_Next(self.V) def LCA(self,a,b): if self.lca_segment_tree: m=min(self.lca_dfs_in_index[a],self.lca_dfs_in_index[b]) M=max(self.lca_dfs_in_index[a],self.lca_dfs_in_index[b]) x=self.lca_euler_tour[self.ST.Fold_Index(m,M+1)] if x>=0: lca=x else: lca=self.lca_parents[~x] else: if self.lca_depth[a]>self.lca_depth[b]: a,b=b,a b=self.lca_PD.Permutation_Doubling(b,self.lca_depth[b]-self.lca_depth[a]) if a!=b: for k in range(self.lca_PD.k-1,-1,-1): if self.lca_PD.permutation_doubling[a][k]!=self.lca_PD.permutation_doubling[b][k]: a,b=self.lca_PD.permutation_doubling[a][k],self.lca_PD.permutation_doubling[b][k] a,b=self.lca_PD.permutation_doubling[a][0],self.lca_PD.permutation_doubling[b][0] lca=a return lca def Build_HLD(self,s): self.hld_parents,size,self.hld_depth=self.SIV_DFS(s,parents=True,subtree_size=True,unweighted_dist=True) stack=[s] self.hld_tour=[] self.hld_path_parents=[None]*self.V self.hld_path_parents[s]=s while stack: x=stack.pop() self.hld_tour.append(x) max_size=0 max_size_y=None for y in self.graph[x]: if self.weighted: y,d=y if y==self.hld_parents[x]: continue if max_size<size[y]: max_size=size[y] max_size_y=y for y in self.graph[x]: if self.weighted: y,d=y if y==self.hld_parents[x]: continue if y!=max_size_y: stack.append(y) self.hld_path_parents[y]=y if max_size_y!=None: stack.append(max_size_y) self.hld_path_parents[max_size_y]=self.hld_path_parents[x] self.hld_tour_idx=[None]*self.V for i in range(self.V): self.hld_tour_idx[self.hld_tour[i]]=i def HLD(self,a,b,edge=False): L,R=[],[] while self.hld_path_parents[a]!=self.hld_path_parents[b]: if self.hld_depth[self.hld_path_parents[a]]<self.hld_depth[self.hld_path_parents[b]]: R.append((self.hld_tour_idx[self.hld_path_parents[b]],self.hld_tour_idx[b]+1)) b=self.hld_parents[self.hld_path_parents[b]] else: L.append((self.hld_tour_idx[a]+1,self.hld_tour_idx[self.hld_path_parents[a]])) a=self.hld_parents[self.hld_path_parents[a]] if edge: if self.hld_depth[a]!=self.hld_depth[b]: retu=L+[(self.hld_tour_idx[a]+1,self.hld_tour_idx[b]+1)]+R[::-1] else: retu=L+R[::-1] else: if self.hld_depth[a]<self.hld_depth[b]: retu=L+[(self.hld_tour_idx[a],self.hld_tour_idx[b]+1)]+R[::-1] else: retu=L+[(self.hld_tour_idx[a]+1,self.hld_tour_idx[b])]+R[::-1] return retu def Build_Hash(self,s,random_number=False,mod=(1<<61)-1,rerooting=False): self.lower_hash=[None]*self.V if random_number: self.hash_random_number=random_number else: self.hash_random_number=[random.randint(1,10**10) for i in range(self.V)] self.hash_mod=mod parents,postorder,preorder=self.SIV_DFS(s,parents=True,postorder=True,preorder=True) for x in postorder: level=0 for y in self.graph[x]: if self.weighted: y,d=y if y==parents[x]: continue h,l=self.lower_hash[y] level=max(level,l+1) ha=1 for y in self.graph[x]: if self.weighted: y,d=y if y==parents[x]: continue h,l=self.lower_hash[y] ha*=h+self.hash_random_number[l] ha%=self.hash_mod self.lower_hash[x]=(ha,level) if rerooting: self.upper_hash=[None]*self.V self.upper_hash[s]=(1,-1) for x in preorder: children=[y for y,d in self.graph[x] if y!=parents[x]] if self.weighted else [y for y in self.graph[x] if y!=parents[x]] if children: l=len(children) l_lst,r_lst=[None]*(l+1),[None]*(l+1) l_lst[0],r_lst[l]=(1,-1),(1,-1) for i in range(1,l+1): h0,l0=l_lst[i-1] h1,l1=self.lower_hash[children[i-1]] l_lst[i]=(h0*(h1+self.hash_random_number[l1])%self.hash_mod,max(l0,l1)) for i in range(l-1,-1,-1): h0,l0=r_lst[i+1] h1,l1=self.lower_hash[children[i]] r_lst[i]=(h0*(h1+self.hash_random_number[l1])%self.hash_mod,max(l0,l1)) for i in range(l): if x==s: ha,level=1,0 else: ha,level=self.upper_hash[x] h0,l0=l_lst[i] h1,l1=r_lst[i+1] ha*=h0*h1 level=max(level,l0+1,l1+1) ha+=self.hash_random_number[level] ha%=self.hash_mod level+=1 self.upper_hash[children[i]]=(ha,level) return def Hash(self,root,subtree=False): if subtree: ha,level=self.lower_hash[root] ha+=self.hash_random_number[level] ha%=self.hash_mod else: h0,l0=self.lower_hash[root] h1,l1=self.upper_hash[root] ha=(h0*h1+self.hash_random_number[max(l0,l1)])%self.hash_mod level=max(l0,l1) return ha,level def Build_Rerooting(self,s,f_transition,f_merge): self.rerooting_s=s self.rerooting_f_transition=f_transition self.rerooting_f_merge=f_merge parents,postorder,preorder=self.SIV_DFS(s,parents=True,postorder=True,preorder=True) self.rerooting_lower_dp=[None]*self.V for x in postorder: self.rerooting_lower_dp[x]=self.rerooting_f_merge([self.rerooting_f_transition(self.rerooting_lower_dp[y]) for y in G.graph[x] if y!=parents[x]]) self.rerooting_upper_dp=[None]*self.V for x in preorder: children=[y for y in self.graph[x] if y!=parents[x]] left_accumule_f=[None]*(len(children)+1) right_accumule_f=[None]*(len(children)+1) left_accumule_f[0]=self.rerooting_f_merge([]) for i in range(1,len(children)+1): left_accumule_f[i]=self.rerooting_f_merge([left_accumule_f[i-1],self.rerooting_f_transition(self.rerooting_lower_dp[children[i-1]])]) right_accumule_f[len(children)]=self.rerooting_f_merge([]) for i in range(len(children)-1,-1,-1): right_accumule_f[i]=self.rerooting_f_merge([right_accumule_f[i+1],self.rerooting_f_transition(self.rerooting_lower_dp[children[i]])]) for i in range(len(children)): if parents[x]!=None: self.rerooting_upper_dp[children[i]]=self.rerooting_f_merge([left_accumule_f[i],right_accumule_f[i+1],self.rerooting_f_transition(self.rerooting_upper_dp[x])]) else: self.rerooting_upper_dp[children[i]]=self.rerooting_f_merge([left_accumule_f[i],right_accumule_f[i+1]]) def Rerooting(self,x): if x==self.rerooting_s: retu=self.rerooting_lower_dp[x] else: retu=self.rerooting_f_merge([self.rerooting_lower_dp[x],self.rerooting_f_transition(self.rerooting_upper_dp[x])]) return retu def Centroid(self,root=0): x=root parents,size=self.SIV_DFS(x,parents=True,subtree_size=True) while True: for y in self.graph[x]: if self.weighted: y,d=y if y==parents[x]: continue if size[y]*2>size[root]: x=y break else: for y in self.graph[x]: if self.weighted: y,d=y if y==parents[x]: continue if size[root]<=2*size[y]: return x,y return x,None def Centroid_Decomposition(self,edge=False,linked_point=False,point=False,tree=False): if edge: cd_edges_lst=[None]*self.V if linked_point: cd_linked_points=[None]*self.V if point: cd_points_lst=[None]*self.V if tree: cd_tree=[]*self.V edges=self.edges points=[i for i in range(self.V)] prev_centroid=None stack=[(edges,points,None,prev_centroid)] if linked_point else [(edges,points,prev_centroid)] while stack: if linked_point: edges,points,lp,prev_centroid=stack.pop() else: edges,points,prev_centroid=stack.pop() if len(points)==1: centroid=points[0] if edge: cd_edges_lst[centroid]=[] if linked_point: cd_linked_points[centroid]=lp if point: cd_points_lst[centroid]=[centroid] if tree and prev_centroid!=None: cd_tree.append((prev_centroid,centroid)) continue G=Graph(len(points),edges=edges,weighted=self.weighted) centroid,_=G.Centroid() if tree and prev_centroid!=None: cd_tree.append((prev_centroid,points[centroid])) parents,tour=G.SIV_DFS(centroid,parents=True,preorder=True) dp=[None]*len(points) edges_lst=[] points_lst=[] if linked_point: linked_points=[] for i,x in enumerate(G.graph[centroid]): if G.weighted: x,d=x dp[x]=(i,0) edges_lst.append([]) points_lst.append([points[x]]) if linked_point: linked_points.append(points[x]) for x in tour[1:]: for y in G.graph[x]: if G.weighted: y,d=y if y==parents[x]: continue i,j=dp[x] jj=len(points_lst[i]) edges_lst[i].append((j,jj,d) if G.weighted else (j,jj)) points_lst[i].append(points[y]) dp[y]=(i,jj) centroid=points[centroid] if edge: cd_edges_lst[centroid]=edges if linked_point: cd_linked_points[centroid]=lp if point: cd_points_lst[centroid]=points if linked_point: for edges,points,lp in zip(edges_lst,points_lst,linked_points): stack.append((edges,points,lp,centroid)) else: for edges,points in zip(edges_lst,points_lst): stack.append((edges,points,centroid)) retu=() if edge: retu+=(cd_edges_lst,) if linked_point: retu+=(cd_linked_points,) if point: retu+=(cd_points_lst,) if tree: retu+=(cd_tree,) if len(retu)==1: retu=retu[0] return retu def Bridges(self): lowlink,preorder=self.MIV_DFS(lowlink=True,preorder=True) order=[None]*self.V for x in range(self.V): order[preorder[x]]=x bridges=[] for e in self.edges: if self.weighted: x,y,d=e else: x,y=e if order[x]<lowlink[y] or order[y]<lowlink[x]: bridges.append((x,y)) return bridges def Articulation_Points(self): lowlink,parents,preorder=self.MIV_DFS(lowlink=True,parents=True,preorder=True) order=[None]*self.V for x in range(self.V): order[preorder[x]]=x articulation_points=[] for x in range(self.V): if parents[x]==None: if len({y for y in self.graph[x] if parents[y]==x})>=2: articulation_points.append(x) else: for y in self.graph[x]: if parents[y]!=x: continue if order[x]<=lowlink[y]: articulation_points.append(x) break return articulation_points def TECCD(self): lowlink,preorder=self.MIV_DFS(lowlink=True,preorder=True) order=[None]*self.V for x in range(self.V): order[preorder[x]]=x edges=[] for e in self.edges: if self.weighted: x,y,d=e else: x,y=e if order[x]>=lowlink[y] and order[y]>=lowlink[x]: edges.append((x,y)) teccd=Graph(self.V,edges=edges).MIV_DFS(linked_components=True) return teccd def LCD(self): lcd_points=self.MIV_DFS(linked_components=True) lcd_edges=[[] for i in range(len(lcd_points))] idx=[None]*self.V for i in range(len(lcd_points)): for j in range(len(lcd_points[i])): idx[lcd_points[i][j]]=(i,j) for tpl in self.edges: if self.weighted: x,y,d=tpl else: x,y=tpl i,j0=idx[x] i,j1=idx[y] if self.weighted: lcd_edges[i].append((j0,j1,d)) else: lcd_edges[i].append((j0,j1)) return lcd_points,lcd_edges def Dijkstra(self,s,route_restoration=False): dist=[self.inf]*self.V dist[s]=0 hq=[(0,s)] if route_restoration: parents=[None]*self.V while hq: dx,x=heapq.heappop(hq) if dist[x]<dx: continue for y,dy in self.graph[x]: if dist[y]>dx+dy: dist[y]=dx+dy if route_restoration: parents[y]=x heapq.heappush(hq,(dist[y],y)) if route_restoration: return dist,parents else: return dist def Bellman_Ford(self,s,route_restoration=False): dist=[self.inf]*self.V dist[s]=0 if route_restoration: parents=[None]*self.V for _ in range(self.V-1): for i,j,d in self.edges: if dist[j]>dist[i]+d: dist[j]=dist[i]+d if route_restoration: parents[j]=i if not self.directed and dist[i]>dist[j]+d: dist[i]=dist[j]+d if route_restoration: parents[i]=j negative_cycle=[] for i,j,d in self.edges: if dist[j]>dist[i]+d: negative_cycle.append(j) if not self.directed and dist[i]>dist[j]+d: negative_cycle.append(i) if negative_cycle: is_negative_cycle=[False]*self.V for i in negative_cycle: if is_negative_cycle[i]: continue else: queue=[i] is_negative_cycle[i]=True while queue: x=queue.popleft() for y,d in self.graph[x]: if not is_negative_cycle[y]: queue.append(y) is_negative_cycle[y]=True if route_restoration: parents[y]=x for i in range(self.V): if is_negative_cycle[i]: dist[i]=-self.inf if route_restoration: return dist,parents else: return dist def Warshall_Floyd(self,route_restoration=False): dist=[[self.inf]*self.V for i in range(self.V)] for i in range(self.V): dist[i][i]=0 if route_restoration: parents=[[j for j in range(self.V)] for i in range(self.V)] for i,j,d in self.edges: if i==j: continue if dist[i][j]>d: dist[i][j]=d if route_restoration: parents[i][j]=i if not self.directed and dist[j][i]>d: dist[j][i]=d if route_restoration: parents[j][i]=j for k in range(self.V): for i in range(self.V): for j in range(self.V): if dist[i][j]>dist[i][k]+dist[k][j]: dist[i][j]=dist[i][k]+dist[k][j] if route_restoration: parents[i][j]=parents[k][j] for i in range(self.V): if dist[i][i]<0: for j in range(self.V): if dist[i][j]!=self.inf: dist[i][j]=-self.inf if route_restoration: for i in range(self.V): if dist[i][i]==0: parents[i][i]=None return dist,parents else: return dist def BFS_01(self,s,route_restoration=False): queue=deque([s]) seen=[False]*self.V dist=[self.inf]*self.V dist[s]=0 if route_restoration: parents=[None]*self.V while queue: x=queue.popleft() if seen[x]: continue seen[x]=False for y,d in self.graph[x]: if dist[y]>dist[x]+d: dist[y]=dist[x]+d if route_restoration: parents[y]=x if d: queue.append(y) else: queue.appendleft(y) if route_restoration: return dist,parents else: return dist def Distance_Frequency(self): mod=206158430209 cnt=[0]*self.V cd_edges,cd_points,cd_tree=self.Centroid_Decomposition(edge=True,point=True,tree=True) CD=Graph(self.V,edges=cd_tree) parents,tour=CD.SIV_DFS(cd_tree[0][0],parents=True,postorder=True) for x in tour: C=[0]*(len(cd_points[x])+1) for y in CD.graph[x]: if y==parents[x]: continue depth=Graph(len(cd_points[y]),edges=cd_edges[y],weighted=self.weighted).SIV_DFS(0,unweighted_dist=True) CC=[0]*(max(depth)+2) for d in depth: CC[d+1]+=1 cnt[d+1]+=2 C[d+1]+=1 poly=NTT_Pow(CC,2) for d,c in enumerate(poly): if d<self.V: cnt[d]-=c while C and C[-1]==0: C.pop() poly=NTT_Pow(C,2) for d,c in enumerate(poly): if d<N: cnt[d]+=c for i in range(self.V): cnt[i]//=2 return cnt def Shortest_Path_Count(self,s,dist,mod=0): cnt=[0]*self.V cnt[s]=1 for x in sorted([x for x in range(self.V)],key=lambda x:dist[x]): for y in self.graph[x]: if self.weighted: y,d=y else: d=1 if dist[x]+d==dist[y]: cnt[y]+=cnt[x] if mod: cnt[y]%=mod return cnt def K_Shortest_Path_Routing(self,s,t,K,edge_unicursal=False,point_unicursal=False): if point_unicursal: if self.weighted: dist,parents=self.Dijkstra(s,route_restoration=True) else: parents,dist=self.SIV_BFS(s,parents=True,unweighted_dist=True) route=tuple(self.Route_Restoration(s,t,parents)) queue=[(dist[t],route,[dist[x] for x in route])] set_queue=set() set_queue.add(route) retu=[] while queue and K: d,route,route_dist=heapq.heappop(queue) retu.append((d,route,route_dist)) K-=1 set_route=set() for i in range(len(route)-1): x=route[i] set_route.add(x) if self.weighted: edges=[(v,u,d) for u,v,d in self.edges if not u in set_route and not v in set_route] else: edges=[(v,u) for u,v in self.edges if not u in set_route and not v in set_route] G_rev=Graph(self.V,edges=edges,directed=self.directed,weighted=self.weighted,inf=self.inf) if self.weighted: dist_rev,parents_rev=G_rev.Dijkstra(t,route_restoration=True) else: parents_rev,dist_rev=G_rev.SIV_BFS(t,parents=True,unweighted_dist=True) for y in self.graph[x]: if self.weighted: y,d=y else: d=1 if y==route[i+1]: continue if dist_rev[y]==self.inf: continue tpl=route[:i+1]+tuple(self.Route_Restoration(t,y,parents_rev)[::-1]) if not tpl in set_queue: heapq.heappush(queue,(route_dist[i]+d+dist_rev[y],tpl,route_dist[:i+1]+[route_dist[i]+d+dist_rev[y]-dist_rev[z] for z in tpl[i+1:]])) set_queue.add(tpl) elif edge_unicursal: if self.weighted: dist,parents=self.Dijkstra(s,route_restoration=True) else: parents,dist=self.SIV_BFS(s,parents=True,unweighted_dist=True) route=tuple(self.Route_Restoration(s,t,parents)) queue=[(dist[t],route,[dist[x] for x in route])] set_queue=set() set_queue.add(route) retu=[] while queue and K: d,route,route_dist=heapq.heappop(queue) retu.append((d,route,route_dist)) K-=1 set_route=set() for i in range(len(route)-1): x=route[i] y=route[i+1] set_route.add((x,y,route_dist[i+1]-route_dist[i])) if not self.directed: set_route.add((y,x,route_dist[i+1]-route_dist[i])) if self.weighted: edges=[(v,u,d) for u,v,d in self.edges if not (u,v,d) in set_route] else: edges=[(v,u) for u,v in self.edges if not (u,v,d) in set_route] G_rev=Graph(self.V,edges=edges,directed=self.directed,weighted=self.weighted,inf=self.inf) if self.weighted: dist_rev,parents_rev=G_rev.Dijkstra(t,route_restoration=True) else: parents_rev,dist_rev=G_rev.SIV_BFS(t,parents=True,unweighted_dist=True) for y in self.graph[x]: if self.weighted: y,d=y else: d=1 if y==route[i+1]: continue if dist_rev[y]==self.inf: continue tpl=route[:i+1]+tuple(self.Route_Restoration(t,y,parents_rev)[::-1]) if not tpl in set_queue: heapq.heappush(queue,(route_dist[i]+d+dist_rev[y],tpl,route_dist[:i+1]+[route_dist[i]+d+dist_rev[y]-dist_rev[z] for z in tpl[i+1:]])) set_queue.add(tpl) else: if self.weighted: dist,parents=self.Dijkstra(s,route_restoration=True) else: parents,dist=self.SIV_BFS(s,parents=True,unweighted_dist=True) if dist[t]==self.inf: return False route_lst=[tuple(self.Route_Restoration(s,x,parents)) for x in range(self.V)] if self.weighted: edges_rev=[(j,i,d) for i,j,d in self.edges] else: edges_rev=[(j,i) for i,j in self.edges] G_rev=Graph(self.V,edges=edges_rev,weighted=self.weighted,directed=self.directed,inf=self.inf) if self.weighted: dist_rev,parents_rev=G_rev.Dijkstra(t,route_restoration=True) else: parents_rev,dist_rev=G_rev.SIV_BFS(t,parents=True,unweighted_dist=True) route_rev_lst=[] for x in range(self.V): route_rev_lst.append(tuple(self.Route_Restoration(t,x,parents_rev)[::-1])) route=route_lst[t] queue=[(dist[t],route,[dist[x] for x in route])] set_queue=set() set_queue.add(route) retu=[] while queue and K: d,route,route_dist=heapq.heappop(queue) retu.append((d,route,route_dist)) K-=1 for i in range(len(route)): x=route[i] for y in self.graph[x]: if self.weighted: y,d=y else: d=1 if i!=len(route)-1 and y==route[i+1]: continue tpl=route[:i+1]+route_rev_lst[y] if not tpl in set_queue: heapq.heappush(queue,(route_dist[i]+d+dist_rev[y],tpl,route_dist[:i+1]+[route_dist[i]+d+dist_rev[y]-dist_rev[z] for z in route_rev_lst[y]])) set_queue.add(tpl) return retu def Euler_Path(self,s=None,t=None): if self.directed: indegree=[0]*self.V outdegree=[0]*self.V graph=[[] for x in range(self.V)] for tpl in self.edges: if self.weighted: u,v,d=tpl else: u,v=tpl indegree[v]+=1 outdegree[u]+=1 graph[v].append(u) for x in range(self.V): if indegree[x]+1==outdegree[x]: if s==None: s=x elif s!=x: return False elif indegree[x]==outdegree[x]+1: if t==None: t=x elif t!=x: return False elif indegree[x]!=outdegree[x]: return False if (s,t)==(None,None): for x in range(self.V): if graph[x]: s=x t=x break elif s==None: s=t elif t==None: t=s elif s==t: for x in range(self.V): if indegree[x]!=outdegree[x]: return False queue=[t] euler_path=[] while queue: while graph[queue[-1]]: queue.append(graph[queue[-1]].pop()) x=queue.pop() euler_path.append(x) for x in range(self.V): if graph[x]: return False else: degree=[0]*self.V graph=[[] for x in range(self.V)] use_count=[defaultdict(int) for x in range(self.V)] for tpl in self.edges: if self.weighted: u,v,d=tpl else: u,v=tpl degree[v]+=1 degree[u]+=1 graph[u].append(v) graph[v].append(u) for x in range(self.V): if degree[x]%2: if s==None and t!=x: s=x elif t==None and s!=x: t=x elif not x in (s,t): return False if s==None and t==None: for x in range(self.V): if graph[x]: s=x t=x break else: s,t=0,0 elif s==None: s=t elif t==None: t=s elif s!=t: if degree[s]%2==0 or degree[t]%2==0: return False queue=[t] euler_path=[] while queue: while graph[queue[-1]]: if use_count[queue[-1]][graph[queue[-1]][-1]]: use_count[queue[-1]][graph[queue[-1]][-1]]-=1 graph[queue[-1]].pop() else: queue.append(graph[queue[-1]].pop()) use_count[queue[-1]][queue[-2]]+=1 x=queue.pop() euler_path.append(x) for x in range(self.V): if graph[x]: return False if euler_path[0]!=s: return False return euler_path def Route_Restoration(self,s,g,parents): route=[g] while s!=g: if parents[g]==None: route=[] break g=parents[g] route.append(g) route=route[::-1] return route def Negative_Cycls(self): dist=[0]*self.V for _ in range(self.V-1): for i,j,d in self.edges: dist[j]=min(dist[j],dist[i]+d) for i,j,d in self.edges: if dist[j]>dist[i]+d: return True return False def Kruskal(self,maximize=False): UF=UnionFind(self.V) sorted_edges=sorted(self.edges,key=lambda x:x[2],reverse=maximize) spnning_tree=[] for i,j,d in sorted_edges: if not UF.Same(i,j): UF.Union(i,j) spnning_tree.append((i,j,d)) return spnning_tree def Max_Clique(self): graph=[[False]*self.V for x in range(self.V)] for x in range(self.V): for y in self.graph[x]: if self.weighted: y,d=y graph[x][y]=True N0,N1=self.V//2,self.V-self.V//2 pop_count=[sum(bit>>i&1 for i in range(N1)) for bit in range(1<<N1)] is_clique0=[True]*(1<<N0) for j in range(N0): for i in range(j): if not graph[i][j]: is_clique0[1<<i|1<<j]=False for i in range(N0): for bit in range(1<<N0): if bit&1<<i: is_clique0[bit]=is_clique0[bit]&is_clique0[bit^1<<i] is_clique1=[True]*(1<<N1) for j in range(N1): for i in range(j): if not graph[i+N0][j+N0]: is_clique1[1<<i|1<<j]=False for i in range(N1): for bit in range(1<<N1): if bit&1<<i: is_clique1[bit]=is_clique1[bit]&is_clique1[bit^1<<i] max_clique_bit=[bit if is_clique0[bit] else 0 for bit in range(1<<N0)] for i in range(N0): for bit in range(1<<N0): if bit&1<<i and pop_count[max_clique_bit[bit]]<pop_count[max_clique_bit[bit^1<<i]]: max_clique_bit[bit]=max_clique_bit[bit^1<<i] dp=[(1<<N0)-1]*(1<<N1) for j in range(N1): for i in range(N0): if not graph[j+N0][i]: dp[1<<j]^=1<<i for i in range(N1): for bit in range(1<<N1): if bit&1<<i: dp[bit]&=dp[bit^1<<i] bit0,bit1=0,0 for bit in range(1<<N1): if is_clique1[bit] and pop_count[max_clique_bit[dp[bit]]]+pop_count[bit]>pop_count[bit0]+pop_count[bit1]: bit0=max_clique_bit[dp[bit]] bit1=bit max_clique=[i for i in range(N0) if bit0&1<<i]+[i+N0 for i in range(N1) if bit1&1<<i] return max_clique def Cliques(self): graph=[[False]*self.V for x in range(self.V)] for x in range(self.V): for y in self.graph[x]: if self.weighted: y,d=y graph[x][y]=True cliques=[] points=[x for x in range(self.V)] while points: l=len(points) min_degree,min_degree_point=self.inf,None sum_degree=0 for x in points: s=sum(graph[x][y] for y in points) sum_degree+=s if s<min_degree: min_degree=s min_degree_point=x if min_degree**2>=sum_degree: lst=points else: lst=[x for x in points if x==min_degree_point or graph[min_degree_point][x]] l=len(lst) is_clique=[True]*(1<<l) for j in range(l): for i in range(j): if not graph[lst[i]][lst[j]]: is_clique[1<<i|1<<j]=False for i in range(l): for bit in range(1<<l): if bit&1<<i: is_clique[bit]=is_clique[bit]&is_clique[bit^1<<i] if min_degree**2>=sum_degree: for bit in range(1<<l): if is_clique[bit]: cliques.append([lst[i] for i in range(l) if bit&1<<i]) else: idx=lst.index(min_degree_point) for bit in range(1<<l): if is_clique[bit] and bit&1<<idx: cliques.append([lst[i] for i in range(l) if bit&1<<i]) if min_degree**2>=sum_degree: points=[] else: points=[x for x in points if x!=min_degree_point] return cliques def Ford_Fulkerson(self,s,t): max_flow=0 residual_graph=[defaultdict(int) for i in range(self.V)] if self.weighted: for i,j,d in self.edges: if not d: continue residual_graph[i][j]+=d if not self.directed: residual_graph[j][i]+=d else: for i,j in self.edges: residual_graph[i][j]+=1 if not self.directed: residual_graph[j][i]+=1 while True: parents=[None]*self.V parents[s]=s seen=[False]*self.V seen[s]=True queue=deque([s]) while queue: x=queue.popleft() for y in residual_graph[x].keys(): if not seen[y]: seen[y]=True queue.append(y) parents[y]=x if y==t: tt=t while tt!=s: residual_graph[parents[tt]][tt]-=1 residual_graph[tt][parents[tt]]+=1 if not residual_graph[parents[tt]][tt]: residual_graph[parents[tt]].pop(tt) tt=parents[tt] max_flow+=1 break else: continue break else: break return max_flow def BFS(self,s): seen=[False]*self.V seen[s]=True queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) return def DFS(self,s): seen=[False]*self.V finished=[False]*self.V stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) elif not finished[x]: finished[x]=True return N,M=map(int,readline().split()) A=list(map(int,readline().split())) B=list(map(int,readline().split())) for i in range(M): A[i]-=1 B[i]-=1 edges=[] for a,b in zip(A,B): edges.append((a,b)) seen=[False]*N G=Graph(N,edges=edges) parents,depth=G.SIV_DFS(0,parents=True,unweighted_dist=True) ans_lst=[None]*M for i,(a,b) in enumerate(zip(A,B)): if parents[a]==b: if seen[a]: ans_lst[i]=1 else: ans_lst[i]=0 seen[a]=True elif parents[b]==a: if seen[b]: ans_lst[i]=0 else: ans_lst[i]=1 seen[b]=True elif depth[a]<depth[b]: ans_lst[i]=0 else: ans_lst[i]=1 print(*ans_lst,sep="") import bisect import copy import decimal import fractions import heapq import itertools import math import random import sys import time from collections import Counter,deque,defaultdict from functools import lru_cache,reduce from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max def _heappush_max(heap,item): heap.append(item) heapq._siftdown_max(heap, 0, len(heap)-1) def _heappushpop_max(heap, item): if heap and item < heap[0]: item, heap[0] = heap[0], item heapq._siftup_max(heap, 0) return item from math import gcd as GCD read=sys.stdin.read readline=sys.stdin.readline readlines=sys.stdin.readlines import heapq import random from collections import defaultdict,deque class Graph: def __init__(self,V,edges=False,graph=False,directed=False,weighted=False,inf=float("inf")): self.V=V self.directed=directed self.weighted=weighted self.inf=inf if graph: self.graph=graph self.edges=[] for i in range(self.V): if self.weighted: for j,d in self.graph[i]: if self.directed or not self.directed and i<=j: self.edges.append((i,j,d)) else: for j in self.graph[i]: if self.directed or not self.directed and i<=j: self.edges.append((i,j)) else: self.edges=edges self.graph=[[] for i in range(self.V)] if weighted: for i,j,d in self.edges: self.graph[i].append((j,d)) if not self.directed: self.graph[j].append((i,d)) else: for i,j in self.edges: self.graph[i].append(j) if not self.directed: self.graph[j].append(i) def SIV_DFS(self,s,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,lowlink=False,parents=False,postorder=False,preorder=False,subtree_size=False,topological_sort=False,unweighted_dist=False,weighted_dist=False): seen=[False]*self.V finished=[False]*self.V if directed_acyclic or cycle_detection or topological_sort: dag=True if euler_tour: et=[] if linked_components: lc=[] if lowlink: order=[None]*self.V ll=[None]*self.V idx=0 if parents or cycle_detection or lowlink or subtree_size: ps=[None]*self.V if postorder or topological_sort: post=[] if preorder: pre=[] if subtree_size: ss=[1]*self.V if unweighted_dist or bipartite_graph: uwd=[self.inf]*self.V uwd[s]=0 if weighted_dist: wd=[self.inf]*self.V wd[s]=0 stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) if euler_tour: et.append(x) if linked_components: lc.append(x) if lowlink: order[x]=idx ll[x]=idx idx+=1 if preorder: pre.append(x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) if parents or cycle_detection or lowlink or subtree_size: ps[y]=x if unweighted_dist or bipartite_graph: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d elif not finished[y]: if (directed_acyclic or cycle_detection or topological_sort) and dag: dag=False if cycle_detection: cd=(y,x) elif not finished[x]: finished[x]=True if euler_tour: et.append(~x) if lowlink: bl=True for y in self.graph[x]: if self.weighted: y,d=y if ps[x]==y and bl: bl=False continue ll[x]=min(ll[x],order[y]) if x!=s: ll[ps[x]]=min(ll[ps[x]],ll[x]) if postorder or topological_sort: post.append(x) if subtree_size: for y in self.graph[x]: if self.weighted: y,d=y if y==ps[x]: continue ss[x]+=ss[y] if bipartite_graph: bg=[[],[]] for tpl in self.edges: x,y=tpl[:2] if self.weighted else tpl if uwd[x]==self.inf or uwd[y]==self.inf: continue if not uwd[x]%2^uwd[y]%2: bg=False break else: for x in range(self.V): if uwd[x]==self.inf: continue bg[uwd[x]%2].append(x) retu=() if bipartite_graph: retu+=(bg,) if cycle_detection: if dag: cd=[] else: y,x=cd cd=self.Route_Restoration(y,x,ps) retu+=(cd,) if directed_acyclic: retu+=(dag,) if euler_tour: retu+=(et,) if linked_components: retu+=(lc,) if lowlink: retu=(ll,) if parents: retu+=(ps,) if postorder: retu+=(post,) if preorder: retu+=(pre,) if subtree_size: retu+=(ss,) if topological_sort: if dag: tp_sort=post[::-1] else: tp_sort=[] retu+=(tp_sort,) if unweighted_dist: retu+=(uwd,) if weighted_dist: retu+=(wd,) if len(retu)==1: retu=retu[0] return retu def MIV_DFS(self,initial_vertices=None,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,lowlink=False,parents=False,postorder=False,preorder=False,subtree_size=False,topological_sort=False,unweighted_dist=False,weighted_dist=False): if initial_vertices==None: initial_vertices=[s for s in range(self.V)] seen=[False]*self.V finished=[False]*self.V if bipartite_graph: bg=[None]*self.V cnt=-1 if directed_acyclic or cycle_detection or topological_sort: dag=True if euler_tour: et=[] if linked_components: lc=[] if lowlink: order=[None]*self.V ll=[None]*self.V idx=0 if parents or cycle_detection or lowlink or subtree_size: ps=[None]*self.V if postorder or topological_sort: post=[] if preorder: pre=[] if subtree_size: ss=[1]*self.V if bipartite_graph or unweighted_dist: uwd=[self.inf]*self.V if weighted_dist: wd=[self.inf]*self.V for s in initial_vertices: if seen[s]: continue if bipartite_graph: cnt+=1 bg[s]=(cnt,0) if linked_components: lc.append([]) if bipartite_graph or unweighted_dist: uwd[s]=0 if weighted_dist: wd[s]=0 stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) if euler_tour: et.append(x) if linked_components: lc[-1].append(x) if lowlink: order[x]=idx ll[x]=idx idx+=1 if preorder: pre.append(x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) if bipartite_graph: bg[y]=(cnt,bg[x][1]^1) if parents or cycle_detection or lowlink or subtree_size: ps[y]=x if unweighted_dist or bipartite_graph: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d elif not finished[y]: if directed_acyclic and dag: dag=False if cycle_detection: cd=(y,x) elif not finished[x]: finished[x]=True if euler_tour: et.append(~x) if lowlink: bl=True for y in self.graph[x]: if self.weighted: y,d=y if ps[x]==y and bl: bl=False continue ll[x]=min(ll[x],order[y]) if x!=s: ll[ps[x]]=min(ll[ps[x]],ll[x]) if postorder or topological_sort: post.append(x) if subtree_size: for y in self.graph[x]: if self.weighted: y,d=y if y==ps[x]: continue ss[x]+=ss[y] if bipartite_graph: bg_=bg bg=[[[],[]] for i in range(cnt+1)] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if not bg_[i][1]^bg_[j][1]: bg[bg_[i][0]]=False for x in range(self.V): if bg[bg_[x][0]]: bg[bg_[x][0]][bg_[x][1]].append(x) retu=() if bipartite_graph: retu+=(bg,) if cycle_detection: if dag: cd=[] else: y,x=cd cd=self.Route_Restoration(y,x,ps) retu+=(cd,) if directed_acyclic: retu+=(dag,) if euler_tour: retu+=(et,) if linked_components: retu+=(lc,) if lowlink: retu=(ll,) if parents: retu+=(ps,) if postorder: retu+=(post,) if preorder: retu+=(pre,) if subtree_size: retu+=(ss,) if topological_sort: if dag: tp_sort=post[::-1] else: tp_sort=[] retu+=(tp_sort,) if unweighted_dist: retu+=(uwd,) if weighted_dist: retu+=(wd,) if len(retu)==1: retu=retu[0] return retu def SIV_BFS(self,s,bfs_tour=False,bipartite_graph=False,linked_components=False,parents=False,unweighted_dist=False,weighted_dist=False): seen=[False]*self.V seen[s]=True if bfs_tour: bt=[s] if linked_components: lc=[s] if parents: ps=[None]*self.V if unweighted_dist or bipartite_graph: uwd=[self.inf]*self.V uwd[s]=0 if weighted_dist: wd=[self.inf]*self.V wd[s]=0 queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) if bfs_tour: bt.append(y) if linked_components: lc.append(y) if parents: ps[y]=x if unweighted_dist or bipartite_graph: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d if bipartite_graph: bg=[[],[]] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if uwd[i]==self.inf or uwd[j]==self.inf: continue if not uwd[i]%2^uwd[j]%2: bg=False break else: for x in range(self.V): if uwd[x]==self.inf: continue bg[uwd[x]%2].append(x) retu=() if bfs_tour: retu+=(bt,) if bipartite_graph: retu+=(bg,) if linked_components: retu+=(lc,) if parents: retu+=(ps,) if unweighted_dist: retu+=(uwd,) if weighted_dist: retu+=(wd,) if len(retu)==1: retu=retu[0] return retu def MIV_BFS(self,initial_vertices=None,bipartite_graph=False,linked_components=False,parents=False,unweighted_dist=False,weighted_dist=False): if initial_vertices==None: initial_vertices=[i for i in range(self.V)] seen=[False]*self.V if bipartite_graph: bg=[None]*self.V cnt=-1 if linked_components: lc=[] if parents: ps=[None]*self.V if unweighted_dist: uwd=[self.inf]*self.V if weighted_dist: wd=[self.inf]*self.V for s in initial_vertices: if seen[s]: continue seen[s]=True if bipartite_graph: cnt+=1 bg[s]=(cnt,0) if linked_components: lc.append([s]) if unweighted_dist: uwd[s]=0 if weighted_dist: wd[s]=0 queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) if bipartite_graph: bg[y]=(cnt,bg[x][1]^1) if linked_components: lc[-1].append(y) if parents: ps[y]=x if unweighted_dist: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d if bipartite_graph: bg_=bg bg=[[[],[]] for i in range(cnt+1)] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if not bg_[i][1]^bg_[j][1]: bg[bg_[i][0]]=False for x in range(self.V): if bg[bg_[x][0]]: bg[bg_[x][0]][bg_[x][1]].append(x) retu=() if bipartite_graph: retu+=(bg,) if linked_components: retu+=(lc,) if parents: retu=(ps,) if unweighted_dist: retu+=(uwd,) if weighted_dist: retu+=(wd,) if len(retu)==1: retu=retu[0] return retu def Tree_Diameter(self,weighted=False): def Farthest_Point(u): dist=self.SIV_BFS(u,weighted_dist=True) if weighted else self.SIV_BFS(u,unweighted_dist=True) fp=0 for i in range(self.V): if dist[fp]<dist[i]: fp=i return fp,dist[fp] u,d=Farthest_Point(0) v,d=Farthest_Point(u) return u,v,d def SCC(self): reverse_graph=[[] for i in range(self.V)] for tpl in self.edges: u,v=tpl[:2] if self.weighted else tpl reverse_graph[v].append(u) postorder=self.MIV_DFS(postorder=True) scc_points=[] seen=[False]*self.V for s in postorder[::-1]: if seen[s]: continue queue=deque([s]) seen[s]=True lst=[] while queue: x=queue.popleft() lst.append(x) for y in reverse_graph[x]: if not seen[y]: seen[y]=True queue.append(y) scc_points.append(lst) l=len(scc_points) idx=[None]*self.V for i in range(l): for x in scc_points[i]: idx[x]=i scc_edges=set() for tpl in self.edges: u,v=tpl[:2] if self.weighted else tpl if idx[u]!=idx[v]: scc_edges.add((idx[u],idx[v])) scc_edges=list(scc_edges) return scc_points,scc_edges def Build_LCA(self,s,segment_tree=False): self.lca_segment_tree=segment_tree if self.lca_segment_tree: self.lca_euler_tour,self.lca_parents,depth=self.SIV_DFS(s,euler_tour=True,parents=True,unweighted_dist=True) self.lca_dfs_in_index=[None]*self.V self.lca_dfs_out_index=[None]*self.V for i,x in enumerate(self.lca_euler_tour): if x>=0: self.lca_dfs_in_index[x]=i else: self.lca_dfs_out_index[~x]=i self.ST=Segment_Tree(2*self.V,lambda x,y:min(x,y),self.V) lst=[None]*(2*self.V) for i in range(2*self.V-1): if self.lca_euler_tour[i]>=0: lst[i]=depth[self.lca_euler_tour[i]] else: lst[i]=depth[self.lca_parents[~self.lca_euler_tour[i]]] lst[2*self.V-1]=-1 self.ST.Build(lst) else: self.lca_parents,self.lca_depth=self.SIV_DFS(s,parents=True,unweighted_dist=True) self.lca_parents[s]=s self.lca_PD=Path_Doubling(self.V,self.lca_parents) self.lca_PD.Build_Next(self.V) def LCA(self,a,b): if self.lca_segment_tree: m=min(self.lca_dfs_in_index[a],self.lca_dfs_in_index[b]) M=max(self.lca_dfs_in_index[a],self.lca_dfs_in_index[b]) x=self.lca_euler_tour[self.ST.Fold_Index(m,M+1)] if x>=0: lca=x else: lca=self.lca_parents[~x] else: if self.lca_depth[a]>self.lca_depth[b]: a,b=b,a b=self.lca_PD.Permutation_Doubling(b,self.lca_depth[b]-self.lca_depth[a]) if a!=b: for k in range(self.lca_PD.k-1,-1,-1): if self.lca_PD.permutation_doubling[a][k]!=self.lca_PD.permutation_doubling[b][k]: a,b=self.lca_PD.permutation_doubling[a][k],self.lca_PD.permutation_doubling[b][k] a,b=self.lca_PD.permutation_doubling[a][0],self.lca_PD.permutation_doubling[b][0] lca=a return lca def Build_HLD(self,s): self.hld_parents,size,self.hld_depth=self.SIV_DFS(s,parents=True,subtree_size=True,unweighted_dist=True) stack=[s] self.hld_tour=[] self.hld_path_parents=[None]*self.V self.hld_path_parents[s]=s while stack: x=stack.pop() self.hld_tour.append(x) max_size=0 max_size_y=None for y in self.graph[x]: if self.weighted: y,d=y if y==self.hld_parents[x]: continue if max_size<size[y]: max_size=size[y] max_size_y=y for y in self.graph[x]: if self.weighted: y,d=y if y==self.hld_parents[x]: continue if y!=max_size_y: stack.append(y) self.hld_path_parents[y]=y if max_size_y!=None: stack.append(max_size_y) self.hld_path_parents[max_size_y]=self.hld_path_parents[x] self.hld_tour_idx=[None]*self.V for i in range(self.V): self.hld_tour_idx[self.hld_tour[i]]=i def HLD(self,a,b,edge=False): L,R=[],[] while self.hld_path_parents[a]!=self.hld_path_parents[b]: if self.hld_depth[self.hld_path_parents[a]]<self.hld_depth[self.hld_path_parents[b]]: R.append((self.hld_tour_idx[self.hld_path_parents[b]],self.hld_tour_idx[b]+1)) b=self.hld_parents[self.hld_path_parents[b]] else: L.append((self.hld_tour_idx[a]+1,self.hld_tour_idx[self.hld_path_parents[a]])) a=self.hld_parents[self.hld_path_parents[a]] if edge: if self.hld_depth[a]!=self.hld_depth[b]: retu=L+[(self.hld_tour_idx[a]+1,self.hld_tour_idx[b]+1)]+R[::-1] else: retu=L+R[::-1] else: if self.hld_depth[a]<self.hld_depth[b]: retu=L+[(self.hld_tour_idx[a],self.hld_tour_idx[b]+1)]+R[::-1] else: retu=L+[(self.hld_tour_idx[a]+1,self.hld_tour_idx[b])]+R[::-1] return retu def Build_Hash(self,s,random_number=False,mod=(1<<61)-1,rerooting=False): self.lower_hash=[None]*self.V if random_number: self.hash_random_number=random_number else: self.hash_random_number=[random.randint(1,10**10) for i in range(self.V)] self.hash_mod=mod parents,postorder,preorder=self.SIV_DFS(s,parents=True,postorder=True,preorder=True) for x in postorder: level=0 for y in self.graph[x]: if self.weighted: y,d=y if y==parents[x]: continue h,l=self.lower_hash[y] level=max(level,l+1) ha=1 for y in self.graph[x]: if self.weighted: y,d=y if y==parents[x]: continue h,l=self.lower_hash[y] ha*=h+self.hash_random_number[l] ha%=self.hash_mod self.lower_hash[x]=(ha,level) if rerooting: self.upper_hash=[None]*self.V self.upper_hash[s]=(1,-1) for x in preorder: children=[y for y,d in self.graph[x] if y!=parents[x]] if self.weighted else [y for y in self.graph[x] if y!=parents[x]] if children: l=len(children) l_lst,r_lst=[None]*(l+1),[None]*(l+1) l_lst[0],r_lst[l]=(1,-1),(1,-1) for i in range(1,l+1): h0,l0=l_lst[i-1] h1,l1=self.lower_hash[children[i-1]] l_lst[i]=(h0*(h1+self.hash_random_number[l1])%self.hash_mod,max(l0,l1)) for i in range(l-1,-1,-1): h0,l0=r_lst[i+1] h1,l1=self.lower_hash[children[i]] r_lst[i]=(h0*(h1+self.hash_random_number[l1])%self.hash_mod,max(l0,l1)) for i in range(l): if x==s: ha,level=1,0 else: ha,level=self.upper_hash[x] h0,l0=l_lst[i] h1,l1=r_lst[i+1] ha*=h0*h1 level=max(level,l0+1,l1+1) ha+=self.hash_random_number[level] ha%=self.hash_mod level+=1 self.upper_hash[children[i]]=(ha,level) return def Hash(self,root,subtree=False): if subtree: ha,level=self.lower_hash[root] ha+=self.hash_random_number[level] ha%=self.hash_mod else: h0,l0=self.lower_hash[root] h1,l1=self.upper_hash[root] ha=(h0*h1+self.hash_random_number[max(l0,l1)])%self.hash_mod level=max(l0,l1) return ha,level def Build_Rerooting(self,s,f_transition,f_merge): self.rerooting_s=s self.rerooting_f_transition=f_transition self.rerooting_f_merge=f_merge parents,postorder,preorder=self.SIV_DFS(s,parents=True,postorder=True,preorder=True) self.rerooting_lower_dp=[None]*self.V for x in postorder: self.rerooting_lower_dp[x]=self.rerooting_f_merge([self.rerooting_f_transition(self.rerooting_lower_dp[y]) for y in G.graph[x] if y!=parents[x]]) self.rerooting_upper_dp=[None]*self.V for x in preorder: children=[y for y in self.graph[x] if y!=parents[x]] left_accumule_f=[None]*(len(children)+1) right_accumule_f=[None]*(len(children)+1) left_accumule_f[0]=self.rerooting_f_merge([]) for i in range(1,len(children)+1): left_accumule_f[i]=self.rerooting_f_merge([left_accumule_f[i-1],self.rerooting_f_transition(self.rerooting_lower_dp[children[i-1]])]) right_accumule_f[len(children)]=self.rerooting_f_merge([]) for i in range(len(children)-1,-1,-1): right_accumule_f[i]=self.rerooting_f_merge([right_accumule_f[i+1],self.rerooting_f_transition(self.rerooting_lower_dp[children[i]])]) for i in range(len(children)): if parents[x]!=None: self.rerooting_upper_dp[children[i]]=self.rerooting_f_merge([left_accumule_f[i],right_accumule_f[i+1],self.rerooting_f_transition(self.rerooting_upper_dp[x])]) else: self.rerooting_upper_dp[children[i]]=self.rerooting_f_merge([left_accumule_f[i],right_accumule_f[i+1]]) def Rerooting(self,x): if x==self.rerooting_s: retu=self.rerooting_lower_dp[x] else: retu=self.rerooting_f_merge([self.rerooting_lower_dp[x],self.rerooting_f_transition(self.rerooting_upper_dp[x])]) return retu def Centroid(self,root=0): x=root parents,size=self.SIV_DFS(x,parents=True,subtree_size=True) while True: for y in self.graph[x]: if self.weighted: y,d=y if y==parents[x]: continue if size[y]*2>size[root]: x=y break else: for y in self.graph[x]: if self.weighted: y,d=y if y==parents[x]: continue if size[root]<=2*size[y]: return x,y return x,None def Centroid_Decomposition(self,edge=False,linked_point=False,point=False,tree=False): if edge: cd_edges_lst=[None]*self.V if linked_point: cd_linked_points=[None]*self.V if point: cd_points_lst=[None]*self.V if tree: cd_tree=[]*self.V edges=self.edges points=[i for i in range(self.V)] prev_centroid=None stack=[(edges,points,None,prev_centroid)] if linked_point else [(edges,points,prev_centroid)] while stack: if linked_point: edges,points,lp,prev_centroid=stack.pop() else: edges,points,prev_centroid=stack.pop() if len(points)==1: centroid=points[0] if edge: cd_edges_lst[centroid]=[] if linked_point: cd_linked_points[centroid]=lp if point: cd_points_lst[centroid]=[centroid] if tree and prev_centroid!=None: cd_tree.append((prev_centroid,centroid)) continue G=Graph(len(points),edges=edges,weighted=self.weighted) centroid,_=G.Centroid() if tree and prev_centroid!=None: cd_tree.append((prev_centroid,points[centroid])) parents,tour=G.SIV_DFS(centroid,parents=True,preorder=True) dp=[None]*len(points) edges_lst=[] points_lst=[] if linked_point: linked_points=[] for i,x in enumerate(G.graph[centroid]): if G.weighted: x,d=x dp[x]=(i,0) edges_lst.append([]) points_lst.append([points[x]]) if linked_point: linked_points.append(points[x]) for x in tour[1:]: for y in G.graph[x]: if G.weighted: y,d=y if y==parents[x]: continue i,j=dp[x] jj=len(points_lst[i]) edges_lst[i].append((j,jj,d) if G.weighted else (j,jj)) points_lst[i].append(points[y]) dp[y]=(i,jj) centroid=points[centroid] if edge: cd_edges_lst[centroid]=edges if linked_point: cd_linked_points[centroid]=lp if point: cd_points_lst[centroid]=points if linked_point: for edges,points,lp in zip(edges_lst,points_lst,linked_points): stack.append((edges,points,lp,centroid)) else: for edges,points in zip(edges_lst,points_lst): stack.append((edges,points,centroid)) retu=() if edge: retu+=(cd_edges_lst,) if linked_point: retu+=(cd_linked_points,) if point: retu+=(cd_points_lst,) if tree: retu+=(cd_tree,) if len(retu)==1: retu=retu[0] return retu def Bridges(self): lowlink,preorder=self.MIV_DFS(lowlink=True,preorder=True) order=[None]*self.V for x in range(self.V): order[preorder[x]]=x bridges=[] for e in self.edges: if self.weighted: x,y,d=e else: x,y=e if order[x]<lowlink[y] or order[y]<lowlink[x]: bridges.append((x,y)) return bridges def Articulation_Points(self): lowlink,parents,preorder=self.MIV_DFS(lowlink=True,parents=True,preorder=True) order=[None]*self.V for x in range(self.V): order[preorder[x]]=x articulation_points=[] for x in range(self.V): if parents[x]==None: if len({y for y in self.graph[x] if parents[y]==x})>=2: articulation_points.append(x) else: for y in self.graph[x]: if parents[y]!=x: continue if order[x]<=lowlink[y]: articulation_points.append(x) break return articulation_points def TECCD(self): lowlink,preorder=self.MIV_DFS(lowlink=True,preorder=True) order=[None]*self.V for x in range(self.V): order[preorder[x]]=x edges=[] for e in self.edges: if self.weighted: x,y,d=e else: x,y=e if order[x]>=lowlink[y] and order[y]>=lowlink[x]: edges.append((x,y)) teccd=Graph(self.V,edges=edges).MIV_DFS(linked_components=True) return teccd def LCD(self): lcd_points=self.MIV_DFS(linked_components=True) lcd_edges=[[] for i in range(len(lcd_points))] idx=[None]*self.V for i in range(len(lcd_points)): for j in range(len(lcd_points[i])): idx[lcd_points[i][j]]=(i,j) for tpl in self.edges: if self.weighted: x,y,d=tpl else: x,y=tpl i,j0=idx[x] i,j1=idx[y] if self.weighted: lcd_edges[i].append((j0,j1,d)) else: lcd_edges[i].append((j0,j1)) return lcd_points,lcd_edges def Dijkstra(self,s,route_restoration=False): dist=[self.inf]*self.V dist[s]=0 hq=[(0,s)] if route_restoration: parents=[None]*self.V while hq: dx,x=heapq.heappop(hq) if dist[x]<dx: continue for y,dy in self.graph[x]: if dist[y]>dx+dy: dist[y]=dx+dy if route_restoration: parents[y]=x heapq.heappush(hq,(dist[y],y)) if route_restoration: return dist,parents else: return dist def Bellman_Ford(self,s,route_restoration=False): dist=[self.inf]*self.V dist[s]=0 if route_restoration: parents=[None]*self.V for _ in range(self.V-1): for i,j,d in self.edges: if dist[j]>dist[i]+d: dist[j]=dist[i]+d if route_restoration: parents[j]=i if not self.directed and dist[i]>dist[j]+d: dist[i]=dist[j]+d if route_restoration: parents[i]=j negative_cycle=[] for i,j,d in self.edges: if dist[j]>dist[i]+d: negative_cycle.append(j) if not self.directed and dist[i]>dist[j]+d: negative_cycle.append(i) if negative_cycle: is_negative_cycle=[False]*self.V for i in negative_cycle: if is_negative_cycle[i]: continue else: queue=[i] is_negative_cycle[i]=True while queue: x=queue.popleft() for y,d in self.graph[x]: if not is_negative_cycle[y]: queue.append(y) is_negative_cycle[y]=True if route_restoration: parents[y]=x for i in range(self.V): if is_negative_cycle[i]: dist[i]=-self.inf if route_restoration: return dist,parents else: return dist def Warshall_Floyd(self,route_restoration=False): dist=[[self.inf]*self.V for i in range(self.V)] for i in range(self.V): dist[i][i]=0 if route_restoration: parents=[[j for j in range(self.V)] for i in range(self.V)] for i,j,d in self.edges: if i==j: continue if dist[i][j]>d: dist[i][j]=d if route_restoration: parents[i][j]=i if not self.directed and dist[j][i]>d: dist[j][i]=d if route_restoration: parents[j][i]=j for k in range(self.V): for i in range(self.V): for j in range(self.V): if dist[i][j]>dist[i][k]+dist[k][j]: dist[i][j]=dist[i][k]+dist[k][j] if route_restoration: parents[i][j]=parents[k][j] for i in range(self.V): if dist[i][i]<0: for j in range(self.V): if dist[i][j]!=self.inf: dist[i][j]=-self.inf if route_restoration: for i in range(self.V): if dist[i][i]==0: parents[i][i]=None return dist,parents else: return dist def BFS_01(self,s,route_restoration=False): queue=deque([s]) seen=[False]*self.V dist=[self.inf]*self.V dist[s]=0 if route_restoration: parents=[None]*self.V while queue: x=queue.popleft() if seen[x]: continue seen[x]=False for y,d in self.graph[x]: if dist[y]>dist[x]+d: dist[y]=dist[x]+d if route_restoration: parents[y]=x if d: queue.append(y) else: queue.appendleft(y) if route_restoration: return dist,parents else: return dist def Distance_Frequency(self): mod=206158430209 cnt=[0]*self.V cd_edges,cd_points,cd_tree=self.Centroid_Decomposition(edge=True,point=True,tree=True) CD=Graph(self.V,edges=cd_tree) parents,tour=CD.SIV_DFS(cd_tree[0][0],parents=True,postorder=True) for x in tour: C=[0]*(len(cd_points[x])+1) for y in CD.graph[x]: if y==parents[x]: continue depth=Graph(len(cd_points[y]),edges=cd_edges[y],weighted=self.weighted).SIV_DFS(0,unweighted_dist=True) CC=[0]*(max(depth)+2) for d in depth: CC[d+1]+=1 cnt[d+1]+=2 C[d+1]+=1 poly=NTT_Pow(CC,2) for d,c in enumerate(poly): if d<self.V: cnt[d]-=c while C and C[-1]==0: C.pop() poly=NTT_Pow(C,2) for d,c in enumerate(poly): if d<N: cnt[d]+=c for i in range(self.V): cnt[i]//=2 return cnt def Shortest_Path_Count(self,s,dist,mod=0): cnt=[0]*self.V cnt[s]=1 for x in sorted([x for x in range(self.V)],key=lambda x:dist[x]): for y in self.graph[x]: if self.weighted: y,d=y else: d=1 if dist[x]+d==dist[y]: cnt[y]+=cnt[x] if mod: cnt[y]%=mod return cnt def K_Shortest_Path_Routing(self,s,t,K,edge_unicursal=False,point_unicursal=False): if point_unicursal: if self.weighted: dist,parents=self.Dijkstra(s,route_restoration=True) else: parents,dist=self.SIV_BFS(s,parents=True,unweighted_dist=True) route=tuple(self.Route_Restoration(s,t,parents)) queue=[(dist[t],route,[dist[x] for x in route])] set_queue=set() set_queue.add(route) retu=[] while queue and K: d,route,route_dist=heapq.heappop(queue) retu.append((d,route,route_dist)) K-=1 set_route=set() for i in range(len(route)-1): x=route[i] set_route.add(x) if self.weighted: edges=[(v,u,d) for u,v,d in self.edges if not u in set_route and not v in set_route] else: edges=[(v,u) for u,v in self.edges if not u in set_route and not v in set_route] G_rev=Graph(self.V,edges=edges,directed=self.directed,weighted=self.weighted,inf=self.inf) if self.weighted: dist_rev,parents_rev=G_rev.Dijkstra(t,route_restoration=True) else: parents_rev,dist_rev=G_rev.SIV_BFS(t,parents=True,unweighted_dist=True) for y in self.graph[x]: if self.weighted: y,d=y else: d=1 if y==route[i+1]: continue if dist_rev[y]==self.inf: continue tpl=route[:i+1]+tuple(self.Route_Restoration(t,y,parents_rev)[::-1]) if not tpl in set_queue: heapq.heappush(queue,(route_dist[i]+d+dist_rev[y],tpl,route_dist[:i+1]+[route_dist[i]+d+dist_rev[y]-dist_rev[z] for z in tpl[i+1:]])) set_queue.add(tpl) elif edge_unicursal: if self.weighted: dist,parents=self.Dijkstra(s,route_restoration=True) else: parents,dist=self.SIV_BFS(s,parents=True,unweighted_dist=True) route=tuple(self.Route_Restoration(s,t,parents)) queue=[(dist[t],route,[dist[x] for x in route])] set_queue=set() set_queue.add(route) retu=[] while queue and K: d,route,route_dist=heapq.heappop(queue) retu.append((d,route,route_dist)) K-=1 set_route=set() for i in range(len(route)-1): x=route[i] y=route[i+1] set_route.add((x,y,route_dist[i+1]-route_dist[i])) if not self.directed: set_route.add((y,x,route_dist[i+1]-route_dist[i])) if self.weighted: edges=[(v,u,d) for u,v,d in self.edges if not (u,v,d) in set_route] else: edges=[(v,u) for u,v in self.edges if not (u,v,d) in set_route] G_rev=Graph(self.V,edges=edges,directed=self.directed,weighted=self.weighted,inf=self.inf) if self.weighted: dist_rev,parents_rev=G_rev.Dijkstra(t,route_restoration=True) else: parents_rev,dist_rev=G_rev.SIV_BFS(t,parents=True,unweighted_dist=True) for y in self.graph[x]: if self.weighted: y,d=y else: d=1 if y==route[i+1]: continue if dist_rev[y]==self.inf: continue tpl=route[:i+1]+tuple(self.Route_Restoration(t,y,parents_rev)[::-1]) if not tpl in set_queue: heapq.heappush(queue,(route_dist[i]+d+dist_rev[y],tpl,route_dist[:i+1]+[route_dist[i]+d+dist_rev[y]-dist_rev[z] for z in tpl[i+1:]])) set_queue.add(tpl) else: if self.weighted: dist,parents=self.Dijkstra(s,route_restoration=True) else: parents,dist=self.SIV_BFS(s,parents=True,unweighted_dist=True) if dist[t]==self.inf: return False route_lst=[tuple(self.Route_Restoration(s,x,parents)) for x in range(self.V)] if self.weighted: edges_rev=[(j,i,d) for i,j,d in self.edges] else: edges_rev=[(j,i) for i,j in self.edges] G_rev=Graph(self.V,edges=edges_rev,weighted=self.weighted,directed=self.directed,inf=self.inf) if self.weighted: dist_rev,parents_rev=G_rev.Dijkstra(t,route_restoration=True) else: parents_rev,dist_rev=G_rev.SIV_BFS(t,parents=True,unweighted_dist=True) route_rev_lst=[] for x in range(self.V): route_rev_lst.append(tuple(self.Route_Restoration(t,x,parents_rev)[::-1])) route=route_lst[t] queue=[(dist[t],route,[dist[x] for x in route])] set_queue=set() set_queue.add(route) retu=[] while queue and K: d,route,route_dist=heapq.heappop(queue) retu.append((d,route,route_dist)) K-=1 for i in range(len(route)): x=route[i] for y in self.graph[x]: if self.weighted: y,d=y else: d=1 if i!=len(route)-1 and y==route[i+1]: continue tpl=route[:i+1]+route_rev_lst[y] if not tpl in set_queue: heapq.heappush(queue,(route_dist[i]+d+dist_rev[y],tpl,route_dist[:i+1]+[route_dist[i]+d+dist_rev[y]-dist_rev[z] for z in route_rev_lst[y]])) set_queue.add(tpl) return retu def Euler_Path(self,s=None,t=None): if self.directed: indegree=[0]*self.V outdegree=[0]*self.V graph=[[] for x in range(self.V)] for tpl in self.edges: if self.weighted: u,v,d=tpl else: u,v=tpl indegree[v]+=1 outdegree[u]+=1 graph[v].append(u) for x in range(self.V): if indegree[x]+1==outdegree[x]: if s==None: s=x elif s!=x: return False elif indegree[x]==outdegree[x]+1: if t==None: t=x elif t!=x: return False elif indegree[x]!=outdegree[x]: return False if (s,t)==(None,None): for x in range(self.V): if graph[x]: s=x t=x break elif s==None: s=t elif t==None: t=s elif s==t: for x in range(self.V): if indegree[x]!=outdegree[x]: return False queue=[t] euler_path=[] while queue: while graph[queue[-1]]: queue.append(graph[queue[-1]].pop()) x=queue.pop() euler_path.append(x) for x in range(self.V): if graph[x]: return False else: degree=[0]*self.V graph=[[] for x in range(self.V)] use_count=[defaultdict(int) for x in range(self.V)] for tpl in self.edges: if self.weighted: u,v,d=tpl else: u,v=tpl degree[v]+=1 degree[u]+=1 graph[u].append(v) graph[v].append(u) for x in range(self.V): if degree[x]%2: if s==None and t!=x: s=x elif t==None and s!=x: t=x elif not x in (s,t): return False if s==None and t==None: for x in range(self.V): if graph[x]: s=x t=x break else: s,t=0,0 elif s==None: s=t elif t==None: t=s elif s!=t: if degree[s]%2==0 or degree[t]%2==0: return False queue=[t] euler_path=[] while queue: while graph[queue[-1]]: if use_count[queue[-1]][graph[queue[-1]][-1]]: use_count[queue[-1]][graph[queue[-1]][-1]]-=1 graph[queue[-1]].pop() else: queue.append(graph[queue[-1]].pop()) use_count[queue[-1]][queue[-2]]+=1 x=queue.pop() euler_path.append(x) for x in range(self.V): if graph[x]: return False if euler_path[0]!=s: return False return euler_path def Route_Restoration(self,s,g,parents): route=[g] while s!=g: if parents[g]==None: route=[] break g=parents[g] route.append(g) route=route[::-1] return route def Negative_Cycls(self): dist=[0]*self.V for _ in range(self.V-1): for i,j,d in self.edges: dist[j]=min(dist[j],dist[i]+d) for i,j,d in self.edges: if dist[j]>dist[i]+d: return True return False def Kruskal(self,maximize=False): UF=UnionFind(self.V) sorted_edges=sorted(self.edges,key=lambda x:x[2],reverse=maximize) spnning_tree=[] for i,j,d in sorted_edges: if not UF.Same(i,j): UF.Union(i,j) spnning_tree.append((i,j,d)) return spnning_tree def Max_Clique(self): graph=[[False]*self.V for x in range(self.V)] for x in range(self.V): for y in self.graph[x]: if self.weighted: y,d=y graph[x][y]=True N0,N1=self.V//2,self.V-self.V//2 pop_count=[sum(bit>>i&1 for i in range(N1)) for bit in range(1<<N1)] is_clique0=[True]*(1<<N0) for j in range(N0): for i in range(j): if not graph[i][j]: is_clique0[1<<i|1<<j]=False for i in range(N0): for bit in range(1<<N0): if bit&1<<i: is_clique0[bit]=is_clique0[bit]&is_clique0[bit^1<<i] is_clique1=[True]*(1<<N1) for j in range(N1): for i in range(j): if not graph[i+N0][j+N0]: is_clique1[1<<i|1<<j]=False for i in range(N1): for bit in range(1<<N1): if bit&1<<i: is_clique1[bit]=is_clique1[bit]&is_clique1[bit^1<<i] max_clique_bit=[bit if is_clique0[bit] else 0 for bit in range(1<<N0)] for i in range(N0): for bit in range(1<<N0): if bit&1<<i and pop_count[max_clique_bit[bit]]<pop_count[max_clique_bit[bit^1<<i]]: max_clique_bit[bit]=max_clique_bit[bit^1<<i] dp=[(1<<N0)-1]*(1<<N1) for j in range(N1): for i in range(N0): if not graph[j+N0][i]: dp[1<<j]^=1<<i for i in range(N1): for bit in range(1<<N1): if bit&1<<i: dp[bit]&=dp[bit^1<<i] bit0,bit1=0,0 for bit in range(1<<N1): if is_clique1[bit] and pop_count[max_clique_bit[dp[bit]]]+pop_count[bit]>pop_count[bit0]+pop_count[bit1]: bit0=max_clique_bit[dp[bit]] bit1=bit max_clique=[i for i in range(N0) if bit0&1<<i]+[i+N0 for i in range(N1) if bit1&1<<i] return max_clique def Cliques(self): graph=[[False]*self.V for x in range(self.V)] for x in range(self.V): for y in self.graph[x]: if self.weighted: y,d=y graph[x][y]=True cliques=[] points=[x for x in range(self.V)] while points: l=len(points) min_degree,min_degree_point=self.inf,None sum_degree=0 for x in points: s=sum(graph[x][y] for y in points) sum_degree+=s if s<min_degree: min_degree=s min_degree_point=x if min_degree**2>=sum_degree: lst=points else: lst=[x for x in points if x==min_degree_point or graph[min_degree_point][x]] l=len(lst) is_clique=[True]*(1<<l) for j in range(l): for i in range(j): if not graph[lst[i]][lst[j]]: is_clique[1<<i|1<<j]=False for i in range(l): for bit in range(1<<l): if bit&1<<i: is_clique[bit]=is_clique[bit]&is_clique[bit^1<<i] if min_degree**2>=sum_degree: for bit in range(1<<l): if is_clique[bit]: cliques.append([lst[i] for i in range(l) if bit&1<<i]) else: idx=lst.index(min_degree_point) for bit in range(1<<l): if is_clique[bit] and bit&1<<idx: cliques.append([lst[i] for i in range(l) if bit&1<<i]) if min_degree**2>=sum_degree: points=[] else: points=[x for x in points if x!=min_degree_point] return cliques def Ford_Fulkerson(self,s,t): max_flow=0 residual_graph=[defaultdict(int) for i in range(self.V)] if self.weighted: for i,j,d in self.edges: if not d: continue residual_graph[i][j]+=d if not self.directed: residual_graph[j][i]+=d else: for i,j in self.edges: residual_graph[i][j]+=1 if not self.directed: residual_graph[j][i]+=1 while True: parents=[None]*self.V parents[s]=s seen=[False]*self.V seen[s]=True queue=deque([s]) while queue: x=queue.popleft() for y in residual_graph[x].keys(): if not seen[y]: seen[y]=True queue.append(y) parents[y]=x if y==t: tt=t while tt!=s: residual_graph[parents[tt]][tt]-=1 residual_graph[tt][parents[tt]]+=1 if not residual_graph[parents[tt]][tt]: residual_graph[parents[tt]].pop(tt) tt=parents[tt] max_flow+=1 break else: continue break else: break return max_flow def BFS(self,s): seen=[False]*self.V seen[s]=True queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) return def DFS(self,s): seen=[False]*self.V finished=[False]*self.V stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) elif not finished[x]: finished[x]=True return N,M=map(int,readline().split()) A=list(map(int,readline().split())) B=list(map(int,readline().split())) for i in range(M): A[i]-=1 B[i]-=1 edges=[] for a,b in zip(A,B): edges.append((a,b)) seen=[False]*N G=Graph(N,edges=edges) parents,depth=G.MIV_DFS(parents=True,unweighted_dist=True) ans_lst=[None]*M for i,(a,b) in enumerate(zip(A,B)): if parents[a]==b: if seen[a]: ans_lst[i]=1 else: ans_lst[i]=0 seen[a]=True elif parents[b]==a: if seen[b]: ans_lst[i]=0 else: ans_lst[i]=1 seen[b]=True elif depth[a]<depth[b]: ans_lst[i]=0 else: ans_lst[i]=1 print(*ans_lst,sep="")
ConDefects/ConDefects/Code/arc143_d/Python/32779304
condefects-python_data_2544
n, m = map(int, input().split()) a = [u - 1 for u in map(int, input().split())] b = [u - 1 for u in map(int, input().split())] edges = [[] for _ in range(n)] for i in range(m): edges[a[i]].append((b[i], i)) edges[b[i]].append((a[i], i)) # DFS ans = [-1] * m visited = [0] * n for root in range(n): if visited[root]: continue todo = [(root, -1)] while todo: u, i = todo.pop() if visited[u]: if u == a[i]: ans[i] = 0 else: ans[i] = 1 continue visited[u] = 1 if i != -1: if u == a[i]: ans[i] = 1 else: ans[i] = 0 for v, j in edges[u]: if not visited[v]: todo.append((v, j)) print(*ans, sep='') n, m = map(int, input().split()) a = [u - 1 for u in map(int, input().split())] b = [u - 1 for u in map(int, input().split())] edges = [[] for _ in range(n)] for i in range(m): edges[a[i]].append((b[i], i)) edges[b[i]].append((a[i], i)) # DFS ans = [0] * m visited = [0] * n for root in range(n): if visited[root]: continue todo = [(root, -1)] while todo: u, i = todo.pop() if visited[u]: if u == a[i]: ans[i] = 0 else: ans[i] = 1 continue visited[u] = 1 if i != -1: if u == a[i]: ans[i] = 1 else: ans[i] = 0 for v, j in edges[u]: if not visited[v]: todo.append((v, j)) print(*ans, sep='')
ConDefects/ConDefects/Code/arc143_d/Python/34822438
condefects-python_data_2545
import sys input = sys.stdin.readline from collections import defaultdict n,m = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) ans = [-1 for i in range(m)] graph = [[] for i in range(n+1)] for i in range(m): ax,bx = a[i],b[i] graph[ax].append((bx,i,0)) graph[bx].append((ax,i,1)) dc = defaultdict(int) dcc = defaultdict(int) seen = [0 for i in range(n+1)] for i in range(1,n+1): if seen[i] == len(graph[i])-1: continue stack = [(i,-1,-1)] while stack: x,o,d = stack.pop() if seen[x] == len(graph[x])-1: continue if ans[o] >= 0: continue if o >= 0: ans[o] = d seen[x] += 1 for y,o,d in graph[x]: if ans[o] >= 0: continue if seen[y] < len(graph[y])-1: if dc[(x,y)] <= 1: stack.append((y,o,d)) dc[(x,y)] += 1 dcc[(x,y)] = d else: ans[o] = dcc[(x,y)] for i in ans: print(max(i,0),end="") print() import sys input = sys.stdin.readline from collections import defaultdict n,m = map(int,input().split()) a = list(map(int,input().split())) b = list(map(int,input().split())) ans = [-1 for i in range(m)] graph = [[] for i in range(n+1)] for i in range(m): ax,bx = a[i],b[i] graph[ax].append((bx,i,0)) graph[bx].append((ax,i,1)) dc = defaultdict(int) dcc = defaultdict(int) seen = [0 for i in range(n+1)] for i in range(1,n+1): if seen[i] == len(graph[i])-1: continue stack = [(i,-1,-1)] while stack: x,o,d = stack.pop() if seen[x] == len(graph[x])-1: continue if ans[o] >= 0: continue if o >= 0: ans[o] = d seen[x] += 1 for y,o,d in graph[x]: if ans[o] >= 0: continue if seen[y] < len(graph[y])-1: if dc[(x,y)] <= 10: stack.append((y,o,d)) dc[(x,y)] += 1 dcc[(x,y)] = d else: ans[o] = dcc[(x,y)] for i in ans: print(max(i,0),end="") print()
ConDefects/ConDefects/Code/arc143_d/Python/32833945
condefects-python_data_2546
from collections import defaultdict def find_bridge(n, s, links, double_links, aaa, bbb, ans): pre_order = 0 q = [s] while q: u = q[-1] if status[u] < len(links[u]): if pre[u] == -1: pre[u] = low[u] = pre_order pre_order += 1 v = links[u][status[u]] status[u] += 1 if v == parents[u]: continue i = double_links[u][v][0] if aaa[i] == v: ans[i] = 1 if pre[v] != -1: low[u] = min(low[u], low[v]) continue q.append(v) parents[v] = u else: q.pop() p = parents[u] if p != -1: low[p] = min(low[p], low[u]) if pre[u] == low[u]: if len(double_links[p][u]) > 1: i, j = double_links[p][u][:2] if aaa[i] == aaa[j]: ans[i] = 0 ans[j] = 1 else: ans[i] = 0 ans[j] = 0 n, m = map(int, input().split()) double_links = [defaultdict(list) for _ in range(n)] aaa = [a - 1 for a in map(int, input().split())] bbb = [b - 1 for b in map(int, input().split())] for i in range(m): a = aaa[i] b = bbb[i] double_links[a][b].append(i) double_links[b][a].append(i) links = [] for u in range(n): links.append(list(double_links[u].keys())) ans = [0] * m pre = [-1] * n low = [1 << 60] * n status = [0] * n parents = [-1] * n for s in range(n): if pre[s] != -1: continue find_bridge(n, s, links, double_links, aaa, bbb, ans) print(''.join(map(str, ans))) from collections import defaultdict def find_bridge(n, s, links, double_links, aaa, bbb, ans): pre_order = 0 q = [s] while q: u = q[-1] if status[u] < len(links[u]): if pre[u] == -1: pre[u] = low[u] = pre_order pre_order += 1 v = links[u][status[u]] status[u] += 1 if v == parents[u]: continue if pre[u] < pre[v]: continue i = double_links[u][v][0] if aaa[i] == v: ans[i] = 1 if pre[v] != -1: low[u] = min(low[u], low[v]) continue q.append(v) parents[v] = u else: q.pop() p = parents[u] if p != -1: low[p] = min(low[p], low[u]) if pre[u] == low[u]: if len(double_links[p][u]) > 1: i, j = double_links[p][u][:2] if aaa[i] == aaa[j]: ans[i] = 0 ans[j] = 1 else: ans[i] = 0 ans[j] = 0 n, m = map(int, input().split()) double_links = [defaultdict(list) for _ in range(n)] aaa = [a - 1 for a in map(int, input().split())] bbb = [b - 1 for b in map(int, input().split())] for i in range(m): a = aaa[i] b = bbb[i] double_links[a][b].append(i) double_links[b][a].append(i) links = [] for u in range(n): links.append(list(double_links[u].keys())) ans = [0] * m pre = [-1] * n low = [1 << 60] * n status = [0] * n parents = [-1] * n for s in range(n): if pre[s] != -1: continue find_bridge(n, s, links, double_links, aaa, bbb, ans) print(''.join(map(str, ans)))
ConDefects/ConDefects/Code/arc143_d/Python/32782502
condefects-python_data_2547
H, W, N = (int(i) for i in input().split()) A = [int(i) for i in input().split()] D = [0] * 26 for i in range(N): D[A[i]] += 1 s = 0 for i in range(25, -1, -1): d = (H // 2 ** i) * (W // 2 ** i) if d - 4 * s < D[i]: print('No') exit() s = D[i] print('Yes') H, W, N = (int(i) for i in input().split()) A = [int(i) for i in input().split()] D = [0] * 26 for i in range(N): D[A[i]] += 1 s = 0 for i in range(25, -1, -1): d = (H // 2 ** i) * (W // 2 ** i) if d - 4 * s < D[i]: print('No') exit() s = D[i] + 4 * s print('Yes')
ConDefects/ConDefects/Code/arc172_a/Python/54670313
condefects-python_data_2548
def check(i, total): pos = H//pow(2,i) * W//pow(2,i) * pow(2,i*2) if pos >= total: return True else: return False H, W, N = map(int,input().split()) A = list(map(int,input().split())) cnt = [0] * 26 for a in A: cnt[a] += 1 total = 0 for i in range(25, -1, -1): total += cnt[i] * pow(2, i*2) if not check(i, total): print("No") exit() print("Yes") def check(i, total): pos = (H//pow(2,i)) * (W//pow(2,i)) * pow(2,i*2) if pos >= total: return True else: return False H, W, N = map(int,input().split()) A = list(map(int,input().split())) cnt = [0] * 26 for a in A: cnt[a] += 1 total = 0 for i in range(25, -1, -1): total += cnt[i] * pow(2, i*2) if not check(i, total): print("No") exit() print("Yes")
ConDefects/ConDefects/Code/arc172_a/Python/51434027
condefects-python_data_2549
ans = "Yes" h,w,n = map(int,input().split()) a = list(map(int,input().split())) a.sort() a.reverse() l =[[h,w]] for i in range(n): x = 2**a[i] y = 2**a[i] m = len(l) for j in range(m): s = l[j][0] t = l[j][1] f = 0 if x <= s and y <= t: l.pop(j) w1 = x h1 = t - y if 0 < h1: p = [w1,h1] p.sort() l.append(p) w2 = s - x h2 = t if 0 < w2: q = [w2,h2] q.sort() l.append(q) l.sort() f = 1 break if f == 0: ans = "No" print(ans) ans = "Yes" h,w,n = map(int,input().split()) a = list(map(int,input().split())) a.sort() a.reverse() l =[[h,w]] for i in range(n): x = 2**a[i] y = 2**a[i] m = len(l) if m == 0: ans = "No" for j in range(m): s = l[j][0] t = l[j][1] f = 0 if x <= s and y <= t: l.pop(j) w1 = x h1 = t - y if 0 < h1: p = [w1,h1] p.sort() l.append(p) w2 = s - x h2 = t if 0 < w2: q = [w2,h2] q.sort() l.append(q) l.sort() f = 1 break if f == 0: ans = "No" print(ans)
ConDefects/ConDefects/Code/arc172_a/Python/52510372
condefects-python_data_2550
from collections import defaultdict H,W,E=map(int,input().split()) A=list(map(int,input().split())) D=defaultdict(int) for a in A: D[a]+=1 D=sorted(D.items(),reverse=True, key=lambda x: x[0]) #print(D) flag=True area=0 for a,n in D: N=(H//(2**a))*(W//(2**a)) area+=(2**a)**2*n #print(a,n,N,area) if area>=(2**a)**2*N: flag=False if flag: print("Yes") else: print("No") from collections import defaultdict H,W,E=map(int,input().split()) A=list(map(int,input().split())) D=defaultdict(int) for a in A: D[a]+=1 D=sorted(D.items(),reverse=True, key=lambda x: x[0]) #print(D) flag=True area=0 for a,n in D: N=(H//(2**a))*(W//(2**a)) area+=(2**a)**2*n #print(a,n,N,area) if area>(2**a)**2*N: flag=False if flag: print("Yes") else: print("No")
ConDefects/ConDefects/Code/arc172_a/Python/51757032
condefects-python_data_2551
h,w,n = map(int,input().split()) a = list(map(int,input().split())) l = [0 for i in range(26)] for i in a: l[i] += 1 now = 0 for i in range(24,-1,-1): ii = 2**i now += l[i]*(ii**2) if now > (h//ii)*(w//ii)*(ii**2): print("No") exit() print("Yes") h,w,n = map(int,input().split()) a = list(map(int,input().split())) l = [0 for i in range(26)] for i in a: l[i] += 1 now = 0 for i in range(25,-1,-1): ii = 2**i now += l[i]*(ii**2) if now > (h//ii)*(w//ii)*(ii**2): print("No") exit() print("Yes")
ConDefects/ConDefects/Code/arc172_a/Python/51114493
condefects-python_data_2552
N = int(input()) A = sorted(list(map(int, input().split())), reverse=True) print('Alice' if A[0] > A[1] + 1 else ('Alice' if (A[N - 1] - N - 1) & 1 else 'Bob')) N = int(input()) A = sorted(list(map(int, input().split())), reverse=True) print('Alice' if A[0] > A[1] + 1 else ('Alice' if (A[0] - N - 1) & 1 else 'Bob'))
ConDefects/ConDefects/Code/arc137_c/Python/30750383
condefects-python_data_2553
n = int(input()) a = list(map(int, input().split())) a = sorted(a) max_n = a[-1] max2_n = a[-2] if max_n - max2_n >= 2: print("Alice") exit() empty = 1 + max_n - n if empty & 2 == 0: print("Bob") else: print("Alice") n = int(input()) a = list(map(int, input().split())) a = sorted(a) max_n = a[-1] max2_n = a[-2] if max_n - max2_n >= 2: print("Alice") exit() empty = 1 + max_n - n if empty % 2 == 0: print("Bob") else: print("Alice")
ConDefects/ConDefects/Code/arc137_c/Python/33252696
condefects-python_data_2554
if __name__ == '__main__': n = int(input()) a = list(map(int, input().split())) x, y = a[n - 2], a[n - 1] if x + 1 < y or (y - x) % 2 == 0: print("Alice") else: print("Bob") if __name__ == '__main__': n = int(input()) a = list(map(int, input().split())) x, y = a[n - 2], a[n - 1] if x + 1 < y or (y - n) % 2 == 0: print("Alice") else: print("Bob")
ConDefects/ConDefects/Code/arc137_c/Python/44903394
condefects-python_data_2555
import sys sys.setrecursionlimit(500005) input = sys.stdin.readline read_str = lambda: input().strip() read_num = lambda: int(input()) read_nums = lambda: map(int, input().split()) read_list = lambda: list(map(int, input().split())) N = int(3e5) + 10 mod = 998244353 def solve(): n = read_num() nums = read_list() if nums[-1] == n - 1: print('Bob') elif nums[-2] + 1 < nums[-1]: print('Alice') elif nums[-1] % 2: print('Alice') else: print('Bob') return solve() import sys sys.setrecursionlimit(500005) input = sys.stdin.readline read_str = lambda: input().strip() read_num = lambda: int(input()) read_nums = lambda: map(int, input().split()) read_list = lambda: list(map(int, input().split())) N = int(3e5) + 10 mod = 998244353 def solve(): n = read_num() nums = read_list() if nums[-1] == n - 1: print('Bob') elif nums[-2] + 1 < nums[-1]: print('Alice') elif (nums[-1] - n + 1) % 2: print('Alice') else: print('Bob') return solve()
ConDefects/ConDefects/Code/arc137_c/Python/32337261
condefects-python_data_2556
N = int(input()) A = list(map(int,input().split())) if A[N-1]-A[N-2] >=2: print("Alice") exit() if N%2 == A[N-1]%2: print("Bob") else: print("Alice") N = int(input()) A = list(map(int,input().split())) if A[N-1]-A[N-2] >=2: print("Alice") exit() if (N-1)%2 == A[N-1]%2: print("Bob") else: print("Alice")
ConDefects/ConDefects/Code/arc137_c/Python/30259633
condefects-python_data_2557
def find_winner(seq): if (max(seq) - len(seq)) % 2 == 0: return 'Alice' else: return 'Bob' n = int(input()) seq = [int(num) for num in input().split()] print(find_winner(seq)) def find_winner(seq): if (seq[-1] - seq[-2]) >= 2: return 'Alice' if (max(seq) - len(seq)) % 2 == 0: return 'Alice' else: return 'Bob' n = int(input()) seq = [int(num) for num in input().split()] print(find_winner(seq))
ConDefects/ConDefects/Code/arc137_c/Python/30509885
condefects-python_data_2558
n = int(input()) a = list(map(int, input().split())) a.sort() if a[-1] - a[-2] >= 2: print("Alice") else: d = sum(t-s-1 for s,t in zip(a, a[1:])) print("Bob" if d % 2 == 0 else "Alice") n = int(input()) a = list(map(int, input().split())) a.sort() if a[-1] - a[-2] >= 2: print("Alice") else: d = sum(t-s-1 for s,t in zip(a, a[1:])) + a[0] print("Bob" if d % 2 == 0 else "Alice")
ConDefects/ConDefects/Code/arc137_c/Python/33142482
condefects-python_data_2559
n = int(input()) As = [int(x) for x in input().split()] if As[-1]-As[-2] > 1: print("Alice") else: if As[-1]-(n-1)%2==1: print("Alice") else: print("Bob") n = int(input()) As = [int(x) for x in input().split()] if As[-1]-As[-2] > 1: print("Alice") else: if (As[-1]-(n-1))%2==1: print("Alice") else: print("Bob")
ConDefects/ConDefects/Code/arc137_c/Python/30317706
condefects-python_data_2560
S, T = map(str, input().split()) for w in range(1, len(S)): S_cut = [] for i in range(w, len(S) + 1, w): S_cut.append(S[i - w : i]) if i + w > len(S): S_cut.append(S[i:]) # print(S_cut) for c in range(w): column = "" for s in S_cut: if c < len(s): column += s[c] # print(c, column) if len(column) >= c and column == T: print("Yes") exit() print("No") S, T = map(str, input().split()) for w in range(1, len(S)): S_cut = [] for i in range(w, len(S) + 1, w): S_cut.append(S[i - w : i]) if i + w > len(S): S_cut.append(S[i:]) # print(S_cut) for c in range(w): column = "" for s in S_cut: if c < len(s): column += s[c] # print(c, column) if column == T: print("Yes") exit() print("No")
ConDefects/ConDefects/Code/abc360_b/Python/55141723
condefects-python_data_2561
import math s, t = input().split() s, t = s.strip(), t.strip() for w in range(1,len(s)): ss = [s[w*i:w*i+w] for i in range(math.ceil(len(s)/w))] ss[-1] += " " * (len(s) % w) x = [*zip(*ss)] for n in x: if t == "".join(n).strip(): print("Yes") exit(0) print("No") import math s, t = input().split() s, t = s.strip(), t.strip() for w in range(1,len(s)): ss = [s[w*i:w*i+w] for i in range(math.ceil(len(s)/w))] ss[-1] += " " * (w - len(s) % w) x = [*zip(*ss)] for n in x: if t == "".join(n).strip(): print("Yes") exit(0) print("No")
ConDefects/ConDefects/Code/abc360_b/Python/55142362
condefects-python_data_2562
import io import sys import itertools import functools import collections import bisect import operator import threading import math import pprint import heapq import time import decimal import string import random sys.setrecursionlimit(3 * 10 ** 5) INF = 10 ** 18 + 7 decimal.getcontext().prec = 18 # def testcase(): # with open("in.txt",mode="w") as input_file: # testS = ''.join(random.choice(string.ascii_uppercase) for _ in range(random.randint(1, 10))) # testT = ''.join(random.choice(string.ascii_uppercase) for _ in range(random.randint(1, 10))) # input_file.write(f"{testS}\n{testT}") # return # _INPUT = """\ # 13 3 5 # """ # sys.stdin = io.StringIO(_INPUT) # ------------------------------------------------ # ------------------------------------------------ N, H, X = map(int, input().split()) P = list(map(int, input().split())) print(bisect.bisect_right(P, X - H) + 1) import io import sys import itertools import functools import collections import bisect import operator import threading import math import pprint import heapq import time import decimal import string import random sys.setrecursionlimit(3 * 10 ** 5) INF = 10 ** 18 + 7 decimal.getcontext().prec = 18 # def testcase(): # with open("in.txt",mode="w") as input_file: # testS = ''.join(random.choice(string.ascii_uppercase) for _ in range(random.randint(1, 10))) # testT = ''.join(random.choice(string.ascii_uppercase) for _ in range(random.randint(1, 10))) # input_file.write(f"{testS}\n{testT}") # return # _INPUT = """\ # 13 3 5 # """ # sys.stdin = io.StringIO(_INPUT) # ------------------------------------------------ # ------------------------------------------------ N, H, X = map(int, input().split()) P = list(map(int, input().split())) print(bisect.bisect_left(P, X - H) + 1)
ConDefects/ConDefects/Code/abc317_a/Python/54270366
condefects-python_data_2563
from bisect import bisect_left as bis N, H, X = map(int, input().split()) P = tuple(map(int, input().split())) print(P[bis(P, X-H)]) from bisect import bisect_left as bis N, H, X = map(int, input().split()) P = tuple(map(int, input().split())) print(bis(P, X-H) + 1)
ConDefects/ConDefects/Code/abc317_a/Python/54526177
condefects-python_data_2564
#0502 N, H, X = map(int, input().split()) P = list(map(int, input().split())) for i in range(N): if H + P[i] > X: print(i + 1) exit() #0502 N, H, X = map(int, input().split()) P = list(map(int, input().split())) for i in range(N): if H + P[i] >= X: print(i + 1) exit()
ConDefects/ConDefects/Code/abc317_a/Python/54511982
condefects-python_data_2565
n,h,x = input().split() p = input() # print(n) # print(h) # print(x) # print(p) split_p = p.split() list_p = list(split_p) # print(list_p) for i in range(0, int(n)): # print(list_p[i]) if int(list_p[i]) >= int(x) - int(h): print(list_p[i]) break else: continue n,h,x = input().split() p = input() # print(n) # print(h) # print(x) # print(p) split_p = p.split() list_p = list(split_p) # print(list_p) for i in range(0, int(n)): # print(list_p[i]) if int(list_p[i]) >= int(x) - int(h): print(i+1) break else: continue
ConDefects/ConDefects/Code/abc317_a/Python/54442354
condefects-python_data_2566
N,H,X=map(int,input().split()) P=list(map(int,input().split())) ans=1 for i in range(N): if H+P[i]<=X: ans+=1 print(ans) N,H,X=map(int,input().split()) P=list(map(int,input().split())) ans=1 for i in range(N): if H+P[i]<X: ans+=1 print(ans)
ConDefects/ConDefects/Code/abc317_a/Python/54312125
condefects-python_data_2567
N, H, X = map(int,input().split()) P = list(map(int,input().split())) for i in range(N): if X < H + P[i]: print(i+1) break N, H, X = map(int,input().split()) P = list(map(int,input().split())) for i in range(N): if X <= H + P[i]: print(i+1) break
ConDefects/ConDefects/Code/abc317_a/Python/54736802
condefects-python_data_2568
n,h,x = map(int,input().split()) l = list(map(int,input().split())) for i in range(n): if x >= h + l[i]: print(i+1) exit() n,h,x = map(int,input().split()) l = list(map(int,input().split())) for i in range(n): if h + l[i] >= x: print(i+1) exit()
ConDefects/ConDefects/Code/abc317_a/Python/54045407
condefects-python_data_2569
N,H,X = map(int,input().split()) P = input() P = P.split() for i in range(N) : PP = int(P[i]) if (X - H) < PP : print(i+1) break N,H,X = map(int,input().split()) P = input() P = P.split() for i in range(N) : PP = int(P[i]) if (X - H) <= PP : print(i+1) break
ConDefects/ConDefects/Code/abc317_a/Python/54270630
condefects-python_data_2570
N, H, X = map(int, list(input().split())) P = list(map(int, input().split())) min_num = 999999 result = 0 for i in range(N): if H + P[i] > X: if min_num > H + P[i]: min_num = H + P[i] result = i + 1 print(result) N, H, X = map(int, list(input().split())) P = list(map(int, input().split())) min_num = 999999 result = 0 for i in range(N): if H + P[i] >= X: if min_num > H + P[i]: min_num = H + P[i] result = i + 1 print(result)
ConDefects/ConDefects/Code/abc317_a/Python/54907933
condefects-python_data_2571
n, h, x = map(int, input().split()) p = list(map(int, input().split())) for i in range(n): if x < p[i]+h: print(i+1) break n, h, x = map(int, input().split()) p = list(map(int, input().split())) for i in range(n): if x <= p[i]+h: print(i+1) break
ConDefects/ConDefects/Code/abc317_a/Python/54045054
condefects-python_data_2572
s = list(input()) ans = [] for i in range(len(s)): ans.append(s[i:len(s)]+s[0:i]) print(min(ans)) print(max(ans)) s = input() ans = [] for i in range(len(s)): ans.append(s[i:len(s)]+s[0:i]) print(min(ans)) print(max(ans))
ConDefects/ConDefects/Code/abc223_b/Python/52785305
condefects-python_data_2573
S = input() words = [S] for i in range(len(S)-1): words.append(S[i:] + S[:i]) words = sorted(words) print(words[0]) print(words[-1]) S = input() words = [S] for i in range(len(S)): words.append(S[i:] + S[:i]) words = sorted(words) print(words[0]) print(words[-1])
ConDefects/ConDefects/Code/abc223_b/Python/53513467
condefects-python_data_2574
s = input() min_,max_ = s,s for i in range(1,len(s)): if min_>s[i:]+s[:i]: min_ = s[i:]+s[:i] else: max_ = s[i:]+s[:i] print(min_) print(max_) s = input() min_,max_ = s,s for i in range(1,len(s)): if min_>s[i:]+s[:i]: min_ = s[i:]+s[:i] if max_<s[i:]+s[:i]: max_ = s[i:]+s[:i] print(min_) print(max_)
ConDefects/ConDefects/Code/abc223_b/Python/53267282
condefects-python_data_2575
N = int(input()) Arr = list(map(int, input().split())) print([n for n in Arr if n % 2 == 0]) N = int(input()) Arr = list(map(int, input().split())) print(" ".join([str(n) for n in Arr if n % 2 == 0]))
ConDefects/ConDefects/Code/abc294_a/Python/45787578
condefects-python_data_2576
n = int(input()) a = list(map(int,input().split())) x = [] for i in range(n): if a[i] % 2 ==0: x.append(a[i]) print(x) n = int(input()) a = list(map(int,input().split())) x = [] for i in range(n): if a[i] % 2 ==0: x.append(a[i]) print(*x,sep = ' ')
ConDefects/ConDefects/Code/abc294_a/Python/45789682
condefects-python_data_2577
n = int(input()) carp = [["#"]] for k in range(1, n + 1): tmp = [] for _ in range(3): for c in carp[k - 1]: tmp.append(c * 3) tmp = list(map(list, tmp)) cen = 3**k // 2 diff = 3 ** (k - 1) // 2 for i in range(3**k): for j in range(3**k): if cen - diff <= i <= cen + diff and cen - diff <= j <= cen + diff: tmp[i][j] = "." carp.append(tmp) for c in carp[n]: print(*c) n = int(input()) carp = [["#"]] for k in range(1, n + 1): tmp = [] for _ in range(3): for c in carp[k - 1]: tmp.append(c * 3) tmp = list(map(list, tmp)) cen = 3**k // 2 diff = 3 ** (k - 1) // 2 for i in range(3**k): for j in range(3**k): if cen - diff <= i <= cen + diff and cen - diff <= j <= cen + diff: tmp[i][j] = "." carp.append(tmp) for c in carp[n]: print(*c, sep="")
ConDefects/ConDefects/Code/abc357_c/Python/55043182
condefects-python_data_2578
import numpy as np def center(size, l, x, y): for i in range(size): for j in range(size): l[i+size+x][j+size+y] = '.' n = int(input()) size = 3**n size_low = 3**(n-1) l0 = np.array([ ['#', '#', '#'], ['#', '.', '#'], ['#', '#', '#'] ]) lk = [['#' for i in range(size)] for j in range(size)] if n == 0: print('.') elif n == 1: for i in l0: print(*i, sep='') else: for i in range(size): for j in range(size): if i % 3 == 1 and j % 3 == 1: lk[i][j] = '.' center(size_low, lk, 0, 0) for i in range(3): for j in range(3): center(3**(n-2), lk, size_low*i, size_low*j) if n > 3: for i in range(3**(n-2)): for j in range(3**(n-2)): center(3, lk, 9*i, 9*j) if n > 4: for i in range(3**(n-3)): for j in range(3**(n-3)): center(9, lk, 27*i, 27*j) if n > 5: for i in range(3**(n-4)): for j in range(3**(n-4)): center(27, lk, 81*i, 81*j) for i in lk: print(*i,sep='') import numpy as np def center(size, l, x, y): for i in range(size): for j in range(size): l[i+size+x][j+size+y] = '.' n = int(input()) size = 3**n size_low = 3**(n-1) l0 = np.array([ ['#', '#', '#'], ['#', '.', '#'], ['#', '#', '#'] ]) lk = [['#' for i in range(size)] for j in range(size)] if n == 0: print('#') elif n == 1: for i in l0: print(*i, sep='') else: for i in range(size): for j in range(size): if i % 3 == 1 and j % 3 == 1: lk[i][j] = '.' center(size_low, lk, 0, 0) for i in range(3): for j in range(3): center(3**(n-2), lk, size_low*i, size_low*j) if n > 3: for i in range(3**(n-2)): for j in range(3**(n-2)): center(3, lk, 9*i, 9*j) if n > 4: for i in range(3**(n-3)): for j in range(3**(n-3)): center(9, lk, 27*i, 27*j) if n > 5: for i in range(3**(n-4)): for j in range(3**(n-4)): center(27, lk, 81*i, 81*j) for i in lk: print(*i,sep='')
ConDefects/ConDefects/Code/abc357_c/Python/55000126
condefects-python_data_2579
Datos = input() Data = [int (num) for num in Datos.split()] if Data[0]*2==Data[1] or (Data[1]*2)+1==Data[1]: print("Yes") else: print("No") Datos = input() Data = [int (num) for num in Datos.split()] if Data[0]*2==Data[1] or (Data[0]*2)+1==Data[1]: print("Yes") else: print("No")
ConDefects/ConDefects/Code/abc285_a/Python/46015071
condefects-python_data_2580
a = input() one = int(a.split()[0]); two = int(a.split()[1]); if two/2 == one: print("Yes"); else: print("No") a = input() one = int(a.split()[0]); two = int(a.split()[1]); if two//2 == one: print("Yes"); else: print("No")
ConDefects/ConDefects/Code/abc285_a/Python/45555418
condefects-python_data_2581
# a = int(input()) # b = input() a, b = map(int, input().split()) # l = list(map(int, input().split())) # l = [input() for _ in range(a)] # l = [list(map(int, input().split())) for _ in range(a)] if b % 2 <= 1: print("Yes") else: print("No") # a = int(input()) # b = input() a, b = map(int, input().split()) # l = list(map(int, input().split())) # l = [input() for _ in range(a)] # l = [list(map(int, input().split())) for _ in range(a)] if b==a*2 or b==a*2+1: print("Yes") else: print("No")
ConDefects/ConDefects/Code/abc285_a/Python/45976942
condefects-python_data_2582
import sys import heapq input = sys.stdin.readline def miss(): return map(int,input().split()) def lmiss(): return list(map(int,input().split())) def ii(): return int(input()) def li(): return list(input()) N, K = miss() A = lmiss() A.sort() ans = set() next = A.copy() flag = set() heapq.heapify(next) while len(ans) != K: x = heapq.heappop(next) if len(next) > 10**6: break for a in A: if a+x in flag: continue flag.add(a+x) heapq.heappush(next,a+x) ans.add(x) print(max(ans)) import sys import heapq input = sys.stdin.readline def miss(): return map(int,input().split()) def lmiss(): return list(map(int,input().split())) def ii(): return int(input()) def li(): return list(input()) N, K = miss() A = lmiss() A.sort() ans = set() next = A.copy() flag = set() heapq.heapify(next) while len(ans) != K: x = heapq.heappop(next) for a in A: if a+x in flag: continue flag.add(a+x) heapq.heappush(next,a+x) ans.add(x) print(max(ans))
ConDefects/ConDefects/Code/abc297_e/Python/46054755
condefects-python_data_2583
from heapq import heappush, heappop n, k = map(int,input().split()) A = list(map(int,input().split())) hq = [] ans = set() for a in A: heappush(hq, a) ans.add(a) for _ in range(k): u = heappop(hq) print(u) for a in A: if u + a not in ans: heappush(hq, u+a) ans.add(u+a) print(u) from heapq import heappush, heappop n, k = map(int,input().split()) A = list(map(int,input().split())) A = list(set(A)) hq = [] ans = set() for a in A: heappush(hq, a) ans.add(a) for _ in range(k): u = heappop(hq) for a in A: if u + a not in ans: heappush(hq, u+a) ans.add(u+a) print(u)
ConDefects/ConDefects/Code/abc297_e/Python/46197532
condefects-python_data_2584
s = list(input()) big = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" small = "abcdefghijklmnopqrstuvwxyz" isBig = False isSmall = False isDifferent = True for i in range(len(s)): if(s[i] in big): isBig = True if(s[i] in small): isSmall = True if(isBig and isSmall): break if(s.count(s[i]) > 1): isDifferent = False break if(isBig == True and isSmall == True and isDifferent == True): print("Yes") else: print("No") s = list(input()) big = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" small = "abcdefghijklmnopqrstuvwxyz" isBig = False isSmall = False isDifferent = True for i in range(len(s)): if(s[i] in big): isBig = True if(s[i] in small): isSmall = True if(s.count(s[i]) > 1): isDifferent = False break if(isBig == True and isSmall == True and isDifferent == True): print("Yes") else: print("No")
ConDefects/ConDefects/Code/abc249_b/Python/45657791
condefects-python_data_2585
S=input() if S.upper()!=S and S.lower()!=S and set(list(S))==len(S): print("Yes") else: print("No") S=input() if S.upper()!=S and S.lower()!=S and len(set(list(S)))==len(S): print("Yes") else: print("No")
ConDefects/ConDefects/Code/abc249_b/Python/45037515
condefects-python_data_2586
n = int(input()) a = list(map(int,input().split())) imos = [0]*(n+1) for i in range(n): imos[0] += a[i] imos[i+1] -= a[i] for i in range(n): imos[i+1] += imos[i] ans = [0]*n if imos[0] != 0: r = 0 for i in range(1,n): r += imos[i]*abs(imos[0]) ans[i] = abs(imos[0]) ans[0] = -r//imos[0] for i in range(n-1): ans[i+1] += ans[i] print("Yes") print(*ans,sep=' ') cal = 0 for i in range(n): cal += a[i]*ans[i] else: x,y = -1,-1 s = 0 flag = True for i in range(n): if imos[i] > 0: flag = False if flag: print("No") exit() flag = True for i in range(n): if imos[i] < 0: flag = False if flag: print("No") exit() for i in range(1,n): s += imos[i] if imos[i] == -1 and x == -1: x = i elif imos[i] == 1: y = i ans = [0]*n if s >= 0: for i in range(n): if i == x: ans[i] = 1+s else: ans[i] = 1 else: for i in range(n): if i == y: ans[i] = 1-s else: ans[i] = 1 for i in range(n-1): ans[i] += ans[i] print("Yes") print(*ans,sep=' ') n = int(input()) a = list(map(int,input().split())) imos = [0]*(n+1) for i in range(n): imos[0] += a[i] imos[i+1] -= a[i] for i in range(n): imos[i+1] += imos[i] ans = [0]*n if imos[0] != 0: r = 0 for i in range(1,n): r += imos[i]*abs(imos[0]) ans[i] = abs(imos[0]) ans[0] = -r//imos[0] for i in range(n-1): ans[i+1] += ans[i] print("Yes") print(*ans,sep=' ') cal = 0 for i in range(n): cal += a[i]*ans[i] else: x,y = -1,-1 s = 0 flag = True for i in range(n): if imos[i] > 0: flag = False if flag: print("No") exit() flag = True for i in range(n): if imos[i] < 0: flag = False if flag: print("No") exit() for i in range(1,n): s += imos[i] if imos[i] == -1 and x == -1: x = i elif imos[i] == 1: y = i ans = [0]*n if s >= 0: for i in range(n): if i == x: ans[i] = 1+s else: ans[i] = 1 else: for i in range(n): if i == y: ans[i] = 1-s else: ans[i] = 1 for i in range(n-1): ans[i+1] += ans[i] print("Yes") print(*ans,sep=' ')
ConDefects/ConDefects/Code/arc153_c/Python/41497158
condefects-python_data_2587
import re import functools import random import sys import os import math from collections import Counter, defaultdict, deque from functools import lru_cache, reduce, cmp_to_key from itertools import accumulate, combinations, permutations from heapq import nsmallest, nlargest, heappushpop, heapify, heappop, heappush from io import BytesIO, IOBase from copy import deepcopy import threading from typing import * from operator import add, xor, mul, ior, iand, itemgetter import bisect BUFSIZE = 4096 inf = float('inf') class FastIO(IOBase): 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): 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): 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): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin = IOWrapper(sys.stdin) sys.stdout = IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def I(): return input() def II(): return int(input()) def MII(): return map(int, input().split()) def LI(): return list(input().split()) def LII(): return list(map(int, input().split())) def GMI(): return map(lambda x: int(x) - 1, input().split()) def LGMI(): return list(map(lambda x: int(x) - 1, input().split())) def solve(): n = II() nums = LII() total = 0 for i in range(n): total += nums[i]*i ans = list(range(n)) if total == 0: print('Yes') print(*ans) elif total > 0: curr = 0 for i in range(n): curr += nums[i] if curr == 1: for j in range(i+1): ans[j] -= total print('Yes') print(*ans) break else: curr = 0 for i in range(n-1, -1, -1): curr += nums[i] if curr == -1: for j in range(i, n): ans[j] += total print('Yes') print(*ans) break else: print('No') else: curr = 0 for i in range(n-1, -1, -1): curr += nums[i] if curr == 1: for j in range(i, n): ans[j] += total print('Yes') print(*ans) break else: curr = 0 for i in range(n): curr += nums[i] if curr == -1: for j in range(i+1): ans[j] += total print('Yes') print(*ans) break else: print('No') if __name__ == '__main__': # t = II() # for _ in range(t): solve() import re import functools import random import sys import os import math from collections import Counter, defaultdict, deque from functools import lru_cache, reduce, cmp_to_key from itertools import accumulate, combinations, permutations from heapq import nsmallest, nlargest, heappushpop, heapify, heappop, heappush from io import BytesIO, IOBase from copy import deepcopy import threading from typing import * from operator import add, xor, mul, ior, iand, itemgetter import bisect BUFSIZE = 4096 inf = float('inf') class FastIO(IOBase): 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): 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): 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): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin = IOWrapper(sys.stdin) sys.stdout = IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def I(): return input() def II(): return int(input()) def MII(): return map(int, input().split()) def LI(): return list(input().split()) def LII(): return list(map(int, input().split())) def GMI(): return map(lambda x: int(x) - 1, input().split()) def LGMI(): return list(map(lambda x: int(x) - 1, input().split())) def solve(): n = II() nums = LII() total = 0 for i in range(n): total += nums[i]*i ans = list(range(n)) if total == 0: print('Yes') print(*ans) elif total > 0: curr = 0 for i in range(n): curr += nums[i] if curr == 1: for j in range(i+1): ans[j] -= total print('Yes') print(*ans) break else: curr = 0 for i in range(n-1, -1, -1): curr += nums[i] if curr == -1: for j in range(i, n): ans[j] += total print('Yes') print(*ans) break else: print('No') else: curr = 0 for i in range(n-1, -1, -1): curr += nums[i] if curr == 1: for j in range(i, n): ans[j] -= total print('Yes') print(*ans) break else: curr = 0 for i in range(n): curr += nums[i] if curr == -1: for j in range(i+1): ans[j] += total print('Yes') print(*ans) break else: print('No') if __name__ == '__main__': # t = II() # for _ in range(t): solve()
ConDefects/ConDefects/Code/arc153_c/Python/38644891
condefects-python_data_2588
import sys import itertools def input(): return sys.stdin.readline().rstrip() def main(): n = int(input()) a = list(map(int, input().split())) b = list(range(n)) pre = list(itertools.accumulate(a, initial=0)) def success(): print("Yes") print(*b) total = sum(i*a[i] for i in range(n)) if total == 0: success() return # make total > 0 if total < 0: total = -total a = [-x for x in a] pre = [-x for x in pre] for i in range(1, n+1): if pre[i] == 1: for j in range(i): b[j] -= total success() return for i in range(n-1, 0, -1): if pre[-1] - pre[i] == -1: for j in range(i, n): b[j] += total success() return print("No") if __name__ == "__main__": main() import sys import itertools def input(): return sys.stdin.readline().rstrip() def main(): n = int(input()) a = list(map(int, input().split())) b = list(range(n)) pre = list(itertools.accumulate(a, initial=0)) def success(): print("Yes") print(*b) total = sum(i*a[i] for i in range(n)) if total == 0: success() return # make total > 0 if total < 0: total = -total a = [-x for x in a] pre = [-x for x in pre] for i in range(1, n+1): if pre[i] == 1: for j in range(i): b[j] -= total success() return for i in range(n): if pre[-1] - pre[i] == -1: for j in range(i, n): b[j] += total success() return print("No") if __name__ == "__main__": main()
ConDefects/ConDefects/Code/arc153_c/Python/38524622
condefects-python_data_2589
from collections import deque, defaultdict, Counter Q = int(input()) num = 1 dq = deque([1]) MOD = 998244353 ans = [] pow10 = [] p = 1 for i in range(600001): pow10.append(p) p = (p*10)%MOD for _ in range(Q): q = input().split() if q[0]=="1": t = int(q[1]) num = (num*10 + t) % MOD dq.append(t) elif q[0]=="2": a = dq.popleft() num -= (a * a*pow10[len(dq)]) num = (num+MOD) % MOD elif q[0]=="3": ans.append(num) print(*ans ,sep='\n') from collections import deque, defaultdict, Counter Q = int(input()) num = 1 dq = deque([1]) MOD = 998244353 ans = [] pow10 = [] p = 1 for i in range(600001): pow10.append(p) p = (p*10)%MOD for _ in range(Q): q = input().split() if q[0]=="1": t = int(q[1]) num = (num*10 + t) % MOD dq.append(t) elif q[0]=="2": a = dq.popleft() num -= (a*pow10[len(dq)]) num = (num+MOD) % MOD elif q[0]=="3": ans.append(num) print(*ans ,sep='\n')
ConDefects/ConDefects/Code/abc298_d/Python/45550904
condefects-python_data_2590
from collections import deque Q = int(input()) q = [list(map(int, input().split())) for _ in range(Q)] MOD = 998244353 def mod_pow(x, n, mod): result = 1 base = x while n > 0: if n % 2 == 1: result = (result * base) % mod base = (base * base) % mod n = n // 2 return result pos = 0 queue = deque([1]) ans = 1 for d in q: if d[0] == 1: queue.append(d[1]) ans = (ans * 10 + d[1]) % MOD elif d[0] == 2: front = queue.popleft() ans = (ans - front * mod_pow(10, len(queue)-1, MOD)) % MOD elif d[0] == 3: print(ans) from collections import deque Q = int(input()) q = [list(map(int, input().split())) for _ in range(Q)] MOD = 998244353 def mod_pow(x, n, mod): result = 1 base = x while n > 0: if n % 2 == 1: result = (result * base) % mod base = (base * base) % mod n = n // 2 return result pos = 0 queue = deque([1]) ans = 1 for d in q: if d[0] == 1: queue.append(d[1]) ans = (ans * 10 + d[1]) % MOD elif d[0] == 2: front = queue.popleft() ans = (ans - front * mod_pow(10, len(queue), MOD)) % MOD elif d[0] == 3: print(ans)
ConDefects/ConDefects/Code/abc298_d/Python/45710768
condefects-python_data_2591
X = int(input()) if X == 0: print("No") elif X < 100: print("No") elif X%100 == 0: print("Yes") X = int(input()) if X == 0: print("No") elif X < 100: print("No") elif X%100 != 0: print("No") elif X%100 == 0: print("Yes")
ConDefects/ConDefects/Code/abc223_a/Python/45815037
condefects-python_data_2592
n=int(input()) if n<100: print("No") else: print("Yes") n=int(input()) if n<100 or n%100!=0: print("No") else: print("Yes")
ConDefects/ConDefects/Code/abc223_a/Python/45813374
condefects-python_data_2593
x = int(input()) print('Yes' if x%100==0 else 'No') x = int(input()) print('Yes' if x%100==0 and x!=0 else 'No')
ConDefects/ConDefects/Code/abc223_a/Python/45714918
condefects-python_data_2594
import heapq N = int(input()) Vs = list() Es = list() inf = 10 **10 for i in range(1, N): Vs.append([i, inf]) Ai, Bi, Xi = map(int, input().split()) Es.append([i+i, Ai, Xi, Bi]) Vs.append([N, inf]) Vs[0][1] = 0 U = [] heapq.heappush(U, (Vs[0][1], Vs[0])) now = heapq.heappop(U)[1] while now[0] != N: i = Es[now[0]-1][0] A = Es[now[0]-1][1] X = Es[now[0]-1][2] B = Es[now[0]-1][3] if Vs[now[0]][1] == inf: Vs[now[0]][1] = now[1] + A heapq.heappush(U, (Vs[now[0]][1], Vs[now[0]])) elif Vs[now[0]][1] > now[1] + A: Vs[now[0]][1] = now[1] + A if Vs[X-1][1] == inf: Vs[X-1][1] = now[1] + B heapq.heappush(U, (Vs[X-1][1], Vs[X-1])) elif Vs[X-1][1] > now[1] + B: Vs[X-1][1] = now[1] + B now = heapq.heappop(U)[1] print(Vs[N-1][1]) import heapq N = int(input()) Vs = list() Es = list() inf = 10 **10 for i in range(1, N): Vs.append([i, inf]) Ai, Bi, Xi = map(int, input().split()) Es.append([i+i, Ai, Xi, Bi]) Vs.append([N, inf]) Vs[0][1] = 0 U = [] heapq.heappush(U, (Vs[0][1], Vs[0])) now = heapq.heappop(U)[1] while now[0] != N: i = Es[now[0]-1][0] A = Es[now[0]-1][1] X = Es[now[0]-1][2] B = Es[now[0]-1][3] if Vs[now[0]][1] == inf: Vs[now[0]][1] = now[1] + A heapq.heappush(U, (Vs[now[0]][1], Vs[now[0]])) elif Vs[now[0]][1] > now[1] + A: Vs[now[0]][1] = now[1] + A heapq.heappush(U, (Vs[now[0]][1], Vs[now[0]])) if Vs[X-1][1] == inf: Vs[X-1][1] = now[1] + B heapq.heappush(U, (Vs[X-1][1], Vs[X-1])) elif Vs[X-1][1] > now[1] + B: Vs[X-1][1] = now[1] + B heapq.heappush(U, (Vs[X-1][1], Vs[X-1])) now = heapq.heappop(U)[1] print(Vs[N-1][1])
ConDefects/ConDefects/Code/abc340_d/Python/54249756
condefects-python_data_2595
# import pypyjit # pypyjit.set_param('max_unroll_recursion=-1') # import sys # sys.setrecursionlimit(10**7) import re # import more_itertools import functools import sys import bisect import math import itertools from collections import deque from collections import defaultdict from collections import Counter from copy import copy, deepcopy from heapq import heapify, heappush, heappop, heappushpop, heapreplace from functools import cmp_to_key as cmpk al = "abcdefghijklmnopqrstuvwxyz" au = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # io # begin fastio import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): 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): 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): 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): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin = IOWrapper(sys.stdin) # sys.stdout = IOWrapper(sys.stdout) _log = True # if False, perr() do notiong import sys import itertools def ii(): return int(sys.stdin.readline().rstrip()) def gl(): return list(map(int, sys.stdin.readline().split())) def gs(): return list(input().split()) def gr(l): res = itertools.groupby(l) return list([(key, len(list(v))) for key, v in res]) def glm(h,w): a = [] for i in range(h): a.append(gl()) return a def gsm(h): a = [] for i in range(h): a.append(input().split()) return a def perr(*l): if _log: print('\033[33m', end = '', file = sys.stderr) print(*l, '\033[0m', file=sys.stderr) def pex(con): pyn(con) exit() def pyn(con, yes = 'Yes', no = 'No'): if con: print(yes) else: print(no) def py(yes = 'Yes'): print(yes) def pn(no = 'No'): print(no) def putedges(g, idx = 0): n = len(g) e = [] cnt2 = 0 for i in range(n): for j in g[i]: cnt2 += 1 e.append((i, j)) m = len(g) print(n, cnt2) for i in e: if idx == 0: print(*[i[0], i[1]]) else: print(*[i[0] + 1, i[1] + 1]) # end io class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) def all_group_members(self): group_members = defaultdict(list) for member in range(self.n): group_members[self.find(member)].append(member) # return group_members return dict(group_members) def __str__(self): return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items()) # begin util/util def rev(a): a = a[:] return list(reversed(a)) def drev(d): newd = {} for k in rev(list(d.keys())): newd[k] = d[k] return newd def dvsort(d): return dict(sorted(d.items(), key = lambda x: x[1])) def dksort(d): return dict(sorted(d.items())) def yn(con, yes = 'Yes', no = 'No'): if con: return yes else: return no def kiriage(n, r): if n % r == 0: return n // r else: return (n // r) + 1 def ketawa(n): ans = 0 s = str(n) for i in s: ans += int(i) return ans def sinhen(n, l): if n < l: return [n] else: return sinhen(n // l, l) + [n % l] import re def search(q, b): return re.search(b, q) def cut_yoko(a, y): a_copy = deepcopy(a) res = [] for x in range(len(a[0])): res.append(a_copy[y][x]) return res def cut_tate(a, x): a_copy = deepcopy(a) res = [] for y in range(len(a)): res.append(a_copy[y][x]) return res def rmwh(a): s = set([len(e) for e in a]) assert len(s) == 1 while not '#' in a[0]: a = a[1:] while not '#' in a[-1]: a = a[:-1] ok = True while True: for y in range(len(a)): if a[y][0] == '#': ok = False if ok: for y in range(len(a)): a[y] = a[y][1:] else: break ok = True while True: for y in range(len(a)): if a[y][-1] == '#': ok = False if ok: for y in range(len(a)): a[y] = a[y][:-1] else: break return a def cntsep(a, b, k): r = a % k m = a - r ans = (b - m) // (k+1) if r > 0: ans -= 1 return ans def compress(a, base = 1): s = set() for e in a: s.add(e) s = list(sorted(s)) d = {} for i in range(len(s)): d[s[i]] = i b = [] for e in a: b.append(d[e] + base) return b # from decimal import * def myround(x, k): if k < 0: return float(Decimal(str(x)).quantize(Decimal('1E' + str(k+1)), rounding = ROUND_HALF_UP)) else: return int(Decimal(str(x)).quantize(Decimal('1E' + str(k+1)), rounding = ROUND_HALF_UP)) def rp(s, d): return s.translate(str.maketrans(d)) def tr(s, a, b): assert len(a) == len(b) res = [] d = {} for i in len(a): d[a] = b[b] return ''.join([d[e] for e in s])# ned # end util/util # begin permutation # https://strangerxxx.hateblo.jp/entry/20220201/1643705539 def next_permutation(a, l = 0, r = None): if r is None: r = len(a) for i in range(r - 2, l - 1, -1): if a[i] < a[i + 1]: for j in range(r - 1, i, -1): if a[i] < a[j]: a[i], a[j] = a[j], a[i] p, q = i + 1, r - 1 while p < q: a[p], a[q] = a[q], a[p] p += 1 q -= 1 return True return False def prev_permutation(a, l = 0, r = None): if r is None: r = len(a) for i in range(r - 2, l - 1, -1): if a[i] > a[i + 1]: for j in range(r - 1, i, -1): if a[i] > a[j]: a[i], a[j] = a[j], a[i] p, q = i + 1, r - 1 while p < q: a[p], a[q] = a[q], a[p] p += 1 q -= 1 return True return False # end permutation # begin math/gcd def lcm2(x, y): return (x * y) // math.gcd(x, y) def lcm3(*ints): return functools.reduce(lcm2, ints) def gcd(*ints): return math.gcd(*ints) # end math/gcd # https://github.com/tatyam-prime/SortedSet/blob/main/SortedSet.py import math from bisect import bisect_left, bisect_right from typing import Generic, Iterable, Iterator, List, Tuple, TypeVar, Optional T = TypeVar('T') class SortedSet(Generic[T]): BUCKET_RATIO = 16 SPLIT_RATIO = 24 def __init__(self, a: Iterable[T] = []) -> None: "Make a new SortedSet from iterable. / O(N) if sorted and unique / O(N log N)" a = list(a) n = len(a) if any(a[i] > a[i + 1] for i in range(n - 1)): a.sort() if any(a[i] >= a[i + 1] for i in range(n - 1)): a, b = [], a for x in b: if not a or a[-1] != x: a.append(x) n = self.size = len(a) num_bucket = int(math.ceil(math.sqrt(n / self.BUCKET_RATIO))) self.a = [a[n * i // num_bucket : n * (i + 1) // num_bucket] for i in range(num_bucket)] def __iter__(self) -> Iterator[T]: for i in self.a: for j in i: yield j def __reversed__(self) -> Iterator[T]: for i in reversed(self.a): for j in reversed(i): yield j def __eq__(self, other) -> bool: return list(self) == list(other) def __len__(self) -> int: return self.size def __repr__(self) -> str: return "SortedSet" + str(self.a) def __str__(self) -> str: s = str(list(self)) return "{" + s[1 : len(s) - 1] + "}" def _position(self, x: T) -> Tuple[List[T], int, int]: "return the bucket, index of the bucket and position in which x should be. self must not be empty." for i, a in enumerate(self.a): if x <= a[-1]: break return (a, i, bisect_left(a, x)) def __contains__(self, x: T) -> bool: if self.size == 0: return False a, _, i = self._position(x) return i != len(a) and a[i] == x def add(self, x: T) -> bool: "Add an element and return True if added. / O(√N)" if self.size == 0: self.a = [[x]] self.size = 1 return True a, b, i = self._position(x) if i != len(a) and a[i] == x: return False a.insert(i, x) self.size += 1 if len(a) > len(self.a) * self.SPLIT_RATIO: mid = len(a) >> 1 self.a[b:b+1] = [a[:mid], a[mid:]] return True def _pop(self, a: List[T], b: int, i: int) -> T: ans = a.pop(i) self.size -= 1 if not a: del self.a[b] return ans def discard(self, x: T) -> bool: "Remove an element and return True if removed. / O(√N)" if self.size == 0: return False a, b, i = self._position(x) if i == len(a) or a[i] != x: return False self._pop(a, b, i) return True def lt(self, x: T) -> Optional[T]: "Find the largest element < x, or None if it doesn't exist." for a in reversed(self.a): if a[0] < x: return a[bisect_left(a, x) - 1] def le(self, x: T) -> Optional[T]: "Find the largest element <= x, or None if it doesn't exist." for a in reversed(self.a): if a[0] <= x: return a[bisect_right(a, x) - 1] def gt(self, x: T) -> Optional[T]: "Find the smallest element > x, or None if it doesn't exist." for a in self.a: if a[-1] > x: return a[bisect_right(a, x)] def ge(self, x: T) -> Optional[T]: "Find the smallest element >= x, or None if it doesn't exist." for a in self.a: if a[-1] >= x: return a[bisect_left(a, x)] def __getitem__(self, i: int) -> T: "Return the i-th element." if i < 0: for a in reversed(self.a): i += len(a) if i >= 0: return a[i] else: for a in self.a: if i < len(a): return a[i] i -= len(a) raise IndexError def pop(self, i: int = -1) -> T: "Pop and return the i-th element." if i < 0: for b, a in enumerate(reversed(self.a)): i += len(a) if i >= 0: return self._pop(a, ~b, i) else: for b, a in enumerate(self.a): if i < len(a): return self._pop(a, b, i) i -= len(a) raise IndexError def index(self, x: T) -> int: "Count the number of elements < x." ans = 0 for a in self.a: if a[-1] >= x: return ans + bisect_left(a, x) ans += len(a) return ans def index_right(self, x: T) -> int: "Count the number of elements <= x." ans = 0 for a in self.a: if a[-1] > x: return ans + bisect_right(a, x) ans += len(a) return ans # https://github.com/tatyam-prime/SortedSet/blob/main/SortedMultiset.py import math from bisect import bisect_left, bisect_right from typing import Generic, Iterable, Iterator, List, Tuple, TypeVar, Optional T = TypeVar('T') class SortedMultiset(Generic[T]): BUCKET_RATIO = 16 SPLIT_RATIO = 24 def __init__(self, a: Iterable[T] = []) -> None: "Make a new SortedMultiset from iterable. / O(N) if sorted / O(N log N)" a = list(a) n = self.size = len(a) if any(a[i] > a[i + 1] for i in range(n - 1)): a.sort() num_bucket = int(math.ceil(math.sqrt(n / self.BUCKET_RATIO))) self.a = [a[n * i // num_bucket : n * (i + 1) // num_bucket] for i in range(num_bucket)] def __iter__(self) -> Iterator[T]: for i in self.a: for j in i: yield j def __reversed__(self) -> Iterator[T]: for i in reversed(self.a): for j in reversed(i): yield j def __eq__(self, other) -> bool: return list(self) == list(other) def __len__(self) -> int: return self.size def __repr__(self) -> str: return "SortedMultiset" + str(self.a) def __str__(self) -> str: s = str(list(self)) return "{" + s[1 : len(s) - 1] + "}" def _position(self, x: T) -> Tuple[List[T], int, int]: "return the bucket, index of the bucket and position in which x should be. self must not be empty." for i, a in enumerate(self.a): if x <= a[-1]: break return (a, i, bisect_left(a, x)) def __contains__(self, x: T) -> bool: if self.size == 0: return False a, _, i = self._position(x) return i != len(a) and a[i] == x def count(self, x: T) -> int: "Count the number of x." return self.index_right(x) - self.index(x) def add(self, x: T) -> None: "Add an element. / O(√N)" if self.size == 0: self.a = [[x]] self.size = 1 return a, b, i = self._position(x) a.insert(i, x) self.size += 1 if len(a) > len(self.a) * self.SPLIT_RATIO: mid = len(a) >> 1 self.a[b:b+1] = [a[:mid], a[mid:]] def _pop(self, a: List[T], b: int, i: int) -> T: ans = a.pop(i) self.size -= 1 if not a: del self.a[b] return ans def discard(self, x: T) -> bool: "Remove an element and return True if removed. / O(√N)" if self.size == 0: return False a, b, i = self._position(x) if i == len(a) or a[i] != x: return False self._pop(a, b, i) return True def lt(self, x: T) -> Optional[T]: "Find the largest element < x, or None if it doesn't exist." for a in reversed(self.a): if a[0] < x: return a[bisect_left(a, x) - 1] def le(self, x: T) -> Optional[T]: "Find the largest element <= x, or None if it doesn't exist." for a in reversed(self.a): if a[0] <= x: return a[bisect_right(a, x) - 1] def gt(self, x: T) -> Optional[T]: "Find the smallest element > x, or None if it doesn't exist." for a in self.a: if a[-1] > x: return a[bisect_right(a, x)] def ge(self, x: T) -> Optional[T]: "Find the smallest element >= x, or None if it doesn't exist." for a in self.a: if a[-1] >= x: return a[bisect_left(a, x)] def __getitem__(self, i: int) -> T: "Return the i-th element." if i < 0: for a in reversed(self.a): i += len(a) if i >= 0: return a[i] else: for a in self.a: if i < len(a): return a[i] i -= len(a) raise IndexError def pop(self, i: int = -1) -> T: "Pop and return the i-th element." if i < 0: for b, a in enumerate(reversed(self.a)): i += len(a) if i >= 0: return self._pop(a, ~b, i) else: for b, a in enumerate(self.a): if i < len(a): return self._pop(a, b, i) i -= len(a) raise IndexError def index(self, x: T) -> int: "count the number of elements < x." ans = 0 for a in self.a: if a[-1] >= x: return ans + bisect_left(a, x) ans += len(a) return ans def index_right(self, x: T) -> int: "count the number of elements <= x." ans = 0 for a in self.a: if a[-1] > x: return ans + bisect_right(a, x) ans += len(a) return ans # https://stackoverflow.com/questions/2501457/what-do-i-use-for-a-max-heap-implementation-in-python#answer-40455775 class Heapq(): # def __init__(self, arr = []): # self.hq = arr # heapify(self.hq) def __init__(self, arr = None): if arr == None: arr = [] self.hq = arr heapify(self.hq) def pop(self): return heappop(self.hq) def append(self, a): heappush(self.hq, a) def __len__(self): return len(self.hq) def __getitem__(self, idx): return self.hq[idx] def __repr__(self): return str(self.hq) class _MaxHeapObj(object): def __init__(self, val): self.val = val def __lt__(self, other): return self.val > other.val def __eq__(self, other): return self.val == other.val def __str__(self): return str(self.val) class Maxheapq(): def __init__(self, arr = []): self.hq = [_MaxHeapObj(e) for e in arr] heapify(self.hq) def pop(self): return heappop(self.hq).val def append(self, a): heappush(self.hq, _MaxHeapObj(a)) def __len__(self): return len(self.hq) def __getitem__(self, idx): return self.hq[idx].val def __repr__(self): return str([e.val for e in self.hq]) def dijkstra(g, st): h = Heapq() h.append((0, st)) vi = set() res = [inf for i in range(len(g))] while len(vi) != n and len(h) != 0: d, now = h.pop() if now in vi: continue vi.add(now) res[now] = d for to in g[now]: if not to in vi: h.append((d + g[now][to], to)) return res def tarjan(g): n = len(g) scc, s, p = [], [], [] q = [i for i in range(n)] state = [0] * n while q: node = q.pop() if node < 0: d = state[~node] - 1 if p[-1] > d: scc.append(s[d:]) del s[d:] p.pop() for v in scc[-1]: state[v] = -1 elif state[node] > 0: while p[-1] > state[node]: p.pop() elif state[node] == 0: s.append(node) p.append(len(s)) state[node] = len(s) q.append(~node) q.extend(g[node]) return scc def top_sort(g): res = [] vi = set() q = deque() din = [0 for i in range(len(g))] for i in range(len(g)): for e in g[i]: din[e] += 1 for i in range(len(din)): if din[i] == 0: q.append(i) while len(q) != 0: st = q.popleft() res.append(st) for to in g[st]: din[to] -= 1 if din[to] == 0: q.append(to) return res # begin combination # https://rin204.github.io/Library-Python/expansion/math/Combination.py import math class Combination: def __init__(self, n, MOD=998244353): n = min(n, MOD - 1) self.fact = [1] * (n + 1) self.invfact = [1] * (n + 1) self.MOD = MOD for i in range(1, n + 1): self.fact[i] = self.fact[i - 1] * i % MOD self.invfact[n] = pow(self.fact[n], MOD - 2, MOD) for i in range(n - 1, -1, -1): self.invfact[i] = self.invfact[i + 1] * (i + 1) % MOD def extend(self, n): le = len(self.fact) if n < le: return self.fact.extend([1] * (n - le + 1)) self.invfact.extend([1] * (n - le + 1)) for i in range(le, n + 1): self.fact[i] = self.fact[i - 1] * i % self.MOD self.invfact[n] = pow(self.fact[n], self.MOD - 2, self.MOD) for i in range(n - 1, le - 1, -1): self.invfact[i] = self.invfact[i + 1] * (i + 1) % self.MOD def nPk(self, n, k): if k < 0 or n < k: return 0 if n >= len(self.fact): self.extend(n) return self.fact[n] * self.invfact[n - k] % self.MOD def nCk(self, n, k): if k < 0 or n < k: return 0 if n >= len(self.fact): self.extend(n) return (self.fact[n] * self.invfact[n - k] % self.MOD) * self.invfact[k] % self.MOD def nHk(self, n, k): if n == 0 and k == 0: return 1 return self.nCk(n + k - 1, k) def Catalan(self, n): return (self.nCk(2 * n, n) - self.nCk(2 * n, n - 1)) % self.MOD def nCk(n, k): return math.comb(n, k) def nCk_mod(n, k, mod = 998244353): if k < 0 or n < k: return 0 res = 1 for i in range(k): res *= (n - i) res %= mod res *= pow((k - i), -1, mod) res %= mod return res # end combination def mbs(a, key): ng = -1 ok = len(a) while abs(ok - ng) > 1: mid = (ok + ng) // 2 if a[mid] >= key: ok = mid else: ng = mid return ok def satlow(f, lower = 0, upper = 10**9): ng = lower ok = upper while abs(ok - ng) > 1: mid = (ok + ng) // 2 if f(mid): ok = mid else: ng = mid return ok def listsatlow(a, f): ng = -1 ok = len(a) while abs(ok - ng) > 1: mid = (ok + ng) // 2 if f(a[mid]): ok = mid else: ng = mid return ok _log=True def pex(con): pyn(con) exit() def yn(con, yes = 'Yes', no = 'No'): if con: return yes else: return no def pp(con, yes = 'Yes', no = 'No'): if con: print(yes) else: print(no) def pyn(con, yes = 'Yes', no = 'No'): if con: print(yes) else: print(no) def py(yes = 'Yes'): print(yes) def pn(no = 'No'): print(no) yes='Yes' no='No' v4 = [[-1, 0], [0, -1], [0, 1], [1, 0]] inf = float('inf') ans = inf cnt=0 #main n = ii() a = glm(n-1, 3) h = Heapq() h.append((0, 0)) vi = set() while len(h) != 0: while len(h) > 0 and h[0][1] in vi: h.pop() (now, st) = h.pop() vi.add(st) if st == n-1: print(now) exit() if not st + 1 in vi: h.append((now + a[st][0], st+1)) if not (st + a[st][1]) in vi: h.append((now + a[st][1], a[st][2] - 1)) # import pypyjit # pypyjit.set_param('max_unroll_recursion=-1') # import sys # sys.setrecursionlimit(10**7) import re # import more_itertools import functools import sys import bisect import math import itertools from collections import deque from collections import defaultdict from collections import Counter from copy import copy, deepcopy from heapq import heapify, heappush, heappop, heappushpop, heapreplace from functools import cmp_to_key as cmpk al = "abcdefghijklmnopqrstuvwxyz" au = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # io # begin fastio import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): 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): 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): 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): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin = IOWrapper(sys.stdin) # sys.stdout = IOWrapper(sys.stdout) _log = True # if False, perr() do notiong import sys import itertools def ii(): return int(sys.stdin.readline().rstrip()) def gl(): return list(map(int, sys.stdin.readline().split())) def gs(): return list(input().split()) def gr(l): res = itertools.groupby(l) return list([(key, len(list(v))) for key, v in res]) def glm(h,w): a = [] for i in range(h): a.append(gl()) return a def gsm(h): a = [] for i in range(h): a.append(input().split()) return a def perr(*l): if _log: print('\033[33m', end = '', file = sys.stderr) print(*l, '\033[0m', file=sys.stderr) def pex(con): pyn(con) exit() def pyn(con, yes = 'Yes', no = 'No'): if con: print(yes) else: print(no) def py(yes = 'Yes'): print(yes) def pn(no = 'No'): print(no) def putedges(g, idx = 0): n = len(g) e = [] cnt2 = 0 for i in range(n): for j in g[i]: cnt2 += 1 e.append((i, j)) m = len(g) print(n, cnt2) for i in e: if idx == 0: print(*[i[0], i[1]]) else: print(*[i[0] + 1, i[1] + 1]) # end io class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) def all_group_members(self): group_members = defaultdict(list) for member in range(self.n): group_members[self.find(member)].append(member) # return group_members return dict(group_members) def __str__(self): return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items()) # begin util/util def rev(a): a = a[:] return list(reversed(a)) def drev(d): newd = {} for k in rev(list(d.keys())): newd[k] = d[k] return newd def dvsort(d): return dict(sorted(d.items(), key = lambda x: x[1])) def dksort(d): return dict(sorted(d.items())) def yn(con, yes = 'Yes', no = 'No'): if con: return yes else: return no def kiriage(n, r): if n % r == 0: return n // r else: return (n // r) + 1 def ketawa(n): ans = 0 s = str(n) for i in s: ans += int(i) return ans def sinhen(n, l): if n < l: return [n] else: return sinhen(n // l, l) + [n % l] import re def search(q, b): return re.search(b, q) def cut_yoko(a, y): a_copy = deepcopy(a) res = [] for x in range(len(a[0])): res.append(a_copy[y][x]) return res def cut_tate(a, x): a_copy = deepcopy(a) res = [] for y in range(len(a)): res.append(a_copy[y][x]) return res def rmwh(a): s = set([len(e) for e in a]) assert len(s) == 1 while not '#' in a[0]: a = a[1:] while not '#' in a[-1]: a = a[:-1] ok = True while True: for y in range(len(a)): if a[y][0] == '#': ok = False if ok: for y in range(len(a)): a[y] = a[y][1:] else: break ok = True while True: for y in range(len(a)): if a[y][-1] == '#': ok = False if ok: for y in range(len(a)): a[y] = a[y][:-1] else: break return a def cntsep(a, b, k): r = a % k m = a - r ans = (b - m) // (k+1) if r > 0: ans -= 1 return ans def compress(a, base = 1): s = set() for e in a: s.add(e) s = list(sorted(s)) d = {} for i in range(len(s)): d[s[i]] = i b = [] for e in a: b.append(d[e] + base) return b # from decimal import * def myround(x, k): if k < 0: return float(Decimal(str(x)).quantize(Decimal('1E' + str(k+1)), rounding = ROUND_HALF_UP)) else: return int(Decimal(str(x)).quantize(Decimal('1E' + str(k+1)), rounding = ROUND_HALF_UP)) def rp(s, d): return s.translate(str.maketrans(d)) def tr(s, a, b): assert len(a) == len(b) res = [] d = {} for i in len(a): d[a] = b[b] return ''.join([d[e] for e in s])# ned # end util/util # begin permutation # https://strangerxxx.hateblo.jp/entry/20220201/1643705539 def next_permutation(a, l = 0, r = None): if r is None: r = len(a) for i in range(r - 2, l - 1, -1): if a[i] < a[i + 1]: for j in range(r - 1, i, -1): if a[i] < a[j]: a[i], a[j] = a[j], a[i] p, q = i + 1, r - 1 while p < q: a[p], a[q] = a[q], a[p] p += 1 q -= 1 return True return False def prev_permutation(a, l = 0, r = None): if r is None: r = len(a) for i in range(r - 2, l - 1, -1): if a[i] > a[i + 1]: for j in range(r - 1, i, -1): if a[i] > a[j]: a[i], a[j] = a[j], a[i] p, q = i + 1, r - 1 while p < q: a[p], a[q] = a[q], a[p] p += 1 q -= 1 return True return False # end permutation # begin math/gcd def lcm2(x, y): return (x * y) // math.gcd(x, y) def lcm3(*ints): return functools.reduce(lcm2, ints) def gcd(*ints): return math.gcd(*ints) # end math/gcd # https://github.com/tatyam-prime/SortedSet/blob/main/SortedSet.py import math from bisect import bisect_left, bisect_right from typing import Generic, Iterable, Iterator, List, Tuple, TypeVar, Optional T = TypeVar('T') class SortedSet(Generic[T]): BUCKET_RATIO = 16 SPLIT_RATIO = 24 def __init__(self, a: Iterable[T] = []) -> None: "Make a new SortedSet from iterable. / O(N) if sorted and unique / O(N log N)" a = list(a) n = len(a) if any(a[i] > a[i + 1] for i in range(n - 1)): a.sort() if any(a[i] >= a[i + 1] for i in range(n - 1)): a, b = [], a for x in b: if not a or a[-1] != x: a.append(x) n = self.size = len(a) num_bucket = int(math.ceil(math.sqrt(n / self.BUCKET_RATIO))) self.a = [a[n * i // num_bucket : n * (i + 1) // num_bucket] for i in range(num_bucket)] def __iter__(self) -> Iterator[T]: for i in self.a: for j in i: yield j def __reversed__(self) -> Iterator[T]: for i in reversed(self.a): for j in reversed(i): yield j def __eq__(self, other) -> bool: return list(self) == list(other) def __len__(self) -> int: return self.size def __repr__(self) -> str: return "SortedSet" + str(self.a) def __str__(self) -> str: s = str(list(self)) return "{" + s[1 : len(s) - 1] + "}" def _position(self, x: T) -> Tuple[List[T], int, int]: "return the bucket, index of the bucket and position in which x should be. self must not be empty." for i, a in enumerate(self.a): if x <= a[-1]: break return (a, i, bisect_left(a, x)) def __contains__(self, x: T) -> bool: if self.size == 0: return False a, _, i = self._position(x) return i != len(a) and a[i] == x def add(self, x: T) -> bool: "Add an element and return True if added. / O(√N)" if self.size == 0: self.a = [[x]] self.size = 1 return True a, b, i = self._position(x) if i != len(a) and a[i] == x: return False a.insert(i, x) self.size += 1 if len(a) > len(self.a) * self.SPLIT_RATIO: mid = len(a) >> 1 self.a[b:b+1] = [a[:mid], a[mid:]] return True def _pop(self, a: List[T], b: int, i: int) -> T: ans = a.pop(i) self.size -= 1 if not a: del self.a[b] return ans def discard(self, x: T) -> bool: "Remove an element and return True if removed. / O(√N)" if self.size == 0: return False a, b, i = self._position(x) if i == len(a) or a[i] != x: return False self._pop(a, b, i) return True def lt(self, x: T) -> Optional[T]: "Find the largest element < x, or None if it doesn't exist." for a in reversed(self.a): if a[0] < x: return a[bisect_left(a, x) - 1] def le(self, x: T) -> Optional[T]: "Find the largest element <= x, or None if it doesn't exist." for a in reversed(self.a): if a[0] <= x: return a[bisect_right(a, x) - 1] def gt(self, x: T) -> Optional[T]: "Find the smallest element > x, or None if it doesn't exist." for a in self.a: if a[-1] > x: return a[bisect_right(a, x)] def ge(self, x: T) -> Optional[T]: "Find the smallest element >= x, or None if it doesn't exist." for a in self.a: if a[-1] >= x: return a[bisect_left(a, x)] def __getitem__(self, i: int) -> T: "Return the i-th element." if i < 0: for a in reversed(self.a): i += len(a) if i >= 0: return a[i] else: for a in self.a: if i < len(a): return a[i] i -= len(a) raise IndexError def pop(self, i: int = -1) -> T: "Pop and return the i-th element." if i < 0: for b, a in enumerate(reversed(self.a)): i += len(a) if i >= 0: return self._pop(a, ~b, i) else: for b, a in enumerate(self.a): if i < len(a): return self._pop(a, b, i) i -= len(a) raise IndexError def index(self, x: T) -> int: "Count the number of elements < x." ans = 0 for a in self.a: if a[-1] >= x: return ans + bisect_left(a, x) ans += len(a) return ans def index_right(self, x: T) -> int: "Count the number of elements <= x." ans = 0 for a in self.a: if a[-1] > x: return ans + bisect_right(a, x) ans += len(a) return ans # https://github.com/tatyam-prime/SortedSet/blob/main/SortedMultiset.py import math from bisect import bisect_left, bisect_right from typing import Generic, Iterable, Iterator, List, Tuple, TypeVar, Optional T = TypeVar('T') class SortedMultiset(Generic[T]): BUCKET_RATIO = 16 SPLIT_RATIO = 24 def __init__(self, a: Iterable[T] = []) -> None: "Make a new SortedMultiset from iterable. / O(N) if sorted / O(N log N)" a = list(a) n = self.size = len(a) if any(a[i] > a[i + 1] for i in range(n - 1)): a.sort() num_bucket = int(math.ceil(math.sqrt(n / self.BUCKET_RATIO))) self.a = [a[n * i // num_bucket : n * (i + 1) // num_bucket] for i in range(num_bucket)] def __iter__(self) -> Iterator[T]: for i in self.a: for j in i: yield j def __reversed__(self) -> Iterator[T]: for i in reversed(self.a): for j in reversed(i): yield j def __eq__(self, other) -> bool: return list(self) == list(other) def __len__(self) -> int: return self.size def __repr__(self) -> str: return "SortedMultiset" + str(self.a) def __str__(self) -> str: s = str(list(self)) return "{" + s[1 : len(s) - 1] + "}" def _position(self, x: T) -> Tuple[List[T], int, int]: "return the bucket, index of the bucket and position in which x should be. self must not be empty." for i, a in enumerate(self.a): if x <= a[-1]: break return (a, i, bisect_left(a, x)) def __contains__(self, x: T) -> bool: if self.size == 0: return False a, _, i = self._position(x) return i != len(a) and a[i] == x def count(self, x: T) -> int: "Count the number of x." return self.index_right(x) - self.index(x) def add(self, x: T) -> None: "Add an element. / O(√N)" if self.size == 0: self.a = [[x]] self.size = 1 return a, b, i = self._position(x) a.insert(i, x) self.size += 1 if len(a) > len(self.a) * self.SPLIT_RATIO: mid = len(a) >> 1 self.a[b:b+1] = [a[:mid], a[mid:]] def _pop(self, a: List[T], b: int, i: int) -> T: ans = a.pop(i) self.size -= 1 if not a: del self.a[b] return ans def discard(self, x: T) -> bool: "Remove an element and return True if removed. / O(√N)" if self.size == 0: return False a, b, i = self._position(x) if i == len(a) or a[i] != x: return False self._pop(a, b, i) return True def lt(self, x: T) -> Optional[T]: "Find the largest element < x, or None if it doesn't exist." for a in reversed(self.a): if a[0] < x: return a[bisect_left(a, x) - 1] def le(self, x: T) -> Optional[T]: "Find the largest element <= x, or None if it doesn't exist." for a in reversed(self.a): if a[0] <= x: return a[bisect_right(a, x) - 1] def gt(self, x: T) -> Optional[T]: "Find the smallest element > x, or None if it doesn't exist." for a in self.a: if a[-1] > x: return a[bisect_right(a, x)] def ge(self, x: T) -> Optional[T]: "Find the smallest element >= x, or None if it doesn't exist." for a in self.a: if a[-1] >= x: return a[bisect_left(a, x)] def __getitem__(self, i: int) -> T: "Return the i-th element." if i < 0: for a in reversed(self.a): i += len(a) if i >= 0: return a[i] else: for a in self.a: if i < len(a): return a[i] i -= len(a) raise IndexError def pop(self, i: int = -1) -> T: "Pop and return the i-th element." if i < 0: for b, a in enumerate(reversed(self.a)): i += len(a) if i >= 0: return self._pop(a, ~b, i) else: for b, a in enumerate(self.a): if i < len(a): return self._pop(a, b, i) i -= len(a) raise IndexError def index(self, x: T) -> int: "count the number of elements < x." ans = 0 for a in self.a: if a[-1] >= x: return ans + bisect_left(a, x) ans += len(a) return ans def index_right(self, x: T) -> int: "count the number of elements <= x." ans = 0 for a in self.a: if a[-1] > x: return ans + bisect_right(a, x) ans += len(a) return ans # https://stackoverflow.com/questions/2501457/what-do-i-use-for-a-max-heap-implementation-in-python#answer-40455775 class Heapq(): # def __init__(self, arr = []): # self.hq = arr # heapify(self.hq) def __init__(self, arr = None): if arr == None: arr = [] self.hq = arr heapify(self.hq) def pop(self): return heappop(self.hq) def append(self, a): heappush(self.hq, a) def __len__(self): return len(self.hq) def __getitem__(self, idx): return self.hq[idx] def __repr__(self): return str(self.hq) class _MaxHeapObj(object): def __init__(self, val): self.val = val def __lt__(self, other): return self.val > other.val def __eq__(self, other): return self.val == other.val def __str__(self): return str(self.val) class Maxheapq(): def __init__(self, arr = []): self.hq = [_MaxHeapObj(e) for e in arr] heapify(self.hq) def pop(self): return heappop(self.hq).val def append(self, a): heappush(self.hq, _MaxHeapObj(a)) def __len__(self): return len(self.hq) def __getitem__(self, idx): return self.hq[idx].val def __repr__(self): return str([e.val for e in self.hq]) def dijkstra(g, st): h = Heapq() h.append((0, st)) vi = set() res = [inf for i in range(len(g))] while len(vi) != n and len(h) != 0: d, now = h.pop() if now in vi: continue vi.add(now) res[now] = d for to in g[now]: if not to in vi: h.append((d + g[now][to], to)) return res def tarjan(g): n = len(g) scc, s, p = [], [], [] q = [i for i in range(n)] state = [0] * n while q: node = q.pop() if node < 0: d = state[~node] - 1 if p[-1] > d: scc.append(s[d:]) del s[d:] p.pop() for v in scc[-1]: state[v] = -1 elif state[node] > 0: while p[-1] > state[node]: p.pop() elif state[node] == 0: s.append(node) p.append(len(s)) state[node] = len(s) q.append(~node) q.extend(g[node]) return scc def top_sort(g): res = [] vi = set() q = deque() din = [0 for i in range(len(g))] for i in range(len(g)): for e in g[i]: din[e] += 1 for i in range(len(din)): if din[i] == 0: q.append(i) while len(q) != 0: st = q.popleft() res.append(st) for to in g[st]: din[to] -= 1 if din[to] == 0: q.append(to) return res # begin combination # https://rin204.github.io/Library-Python/expansion/math/Combination.py import math class Combination: def __init__(self, n, MOD=998244353): n = min(n, MOD - 1) self.fact = [1] * (n + 1) self.invfact = [1] * (n + 1) self.MOD = MOD for i in range(1, n + 1): self.fact[i] = self.fact[i - 1] * i % MOD self.invfact[n] = pow(self.fact[n], MOD - 2, MOD) for i in range(n - 1, -1, -1): self.invfact[i] = self.invfact[i + 1] * (i + 1) % MOD def extend(self, n): le = len(self.fact) if n < le: return self.fact.extend([1] * (n - le + 1)) self.invfact.extend([1] * (n - le + 1)) for i in range(le, n + 1): self.fact[i] = self.fact[i - 1] * i % self.MOD self.invfact[n] = pow(self.fact[n], self.MOD - 2, self.MOD) for i in range(n - 1, le - 1, -1): self.invfact[i] = self.invfact[i + 1] * (i + 1) % self.MOD def nPk(self, n, k): if k < 0 or n < k: return 0 if n >= len(self.fact): self.extend(n) return self.fact[n] * self.invfact[n - k] % self.MOD def nCk(self, n, k): if k < 0 or n < k: return 0 if n >= len(self.fact): self.extend(n) return (self.fact[n] * self.invfact[n - k] % self.MOD) * self.invfact[k] % self.MOD def nHk(self, n, k): if n == 0 and k == 0: return 1 return self.nCk(n + k - 1, k) def Catalan(self, n): return (self.nCk(2 * n, n) - self.nCk(2 * n, n - 1)) % self.MOD def nCk(n, k): return math.comb(n, k) def nCk_mod(n, k, mod = 998244353): if k < 0 or n < k: return 0 res = 1 for i in range(k): res *= (n - i) res %= mod res *= pow((k - i), -1, mod) res %= mod return res # end combination def mbs(a, key): ng = -1 ok = len(a) while abs(ok - ng) > 1: mid = (ok + ng) // 2 if a[mid] >= key: ok = mid else: ng = mid return ok def satlow(f, lower = 0, upper = 10**9): ng = lower ok = upper while abs(ok - ng) > 1: mid = (ok + ng) // 2 if f(mid): ok = mid else: ng = mid return ok def listsatlow(a, f): ng = -1 ok = len(a) while abs(ok - ng) > 1: mid = (ok + ng) // 2 if f(a[mid]): ok = mid else: ng = mid return ok _log=True def pex(con): pyn(con) exit() def yn(con, yes = 'Yes', no = 'No'): if con: return yes else: return no def pp(con, yes = 'Yes', no = 'No'): if con: print(yes) else: print(no) def pyn(con, yes = 'Yes', no = 'No'): if con: print(yes) else: print(no) def py(yes = 'Yes'): print(yes) def pn(no = 'No'): print(no) yes='Yes' no='No' v4 = [[-1, 0], [0, -1], [0, 1], [1, 0]] inf = float('inf') ans = inf cnt=0 #main n = ii() a = glm(n-1, 3) h = Heapq() h.append((0, 0)) vi = set() while len(h) != 0: while len(h) > 0 and h[0][1] in vi: h.pop() (now, st) = h.pop() vi.add(st) if st == n-1: print(now) exit() if not st + 1 in vi: h.append((now + a[st][0], st+1)) if not (a[st][2] - 1) in vi: h.append((now + a[st][1], a[st][2] - 1))
ConDefects/ConDefects/Code/abc340_d/Python/54442427
condefects-python_data_2596
from collections import defaultdict import heapq N = int(input()) G = defaultdict(list) for i in range(1,N): a,b,x = map(int,input().split()) G[i].append((i+1,a)) G[i].append((x,b)) seen = [False] * (N+1) dist = [10**10] * (N+1) dist[1] = 0 q = [(0,1)] heapq.heapify(q) while(len(q)>0): v = heapq.heappop(q)[1] """ E-TrainではこれをつけてTLE改善 if seen[v] == True: continue """ seen[v] = True for next in G[v]: if not seen[next[0]] and dist[next[0]] > dist[v] + next[1]: dist[next[0]] = dist[v] + next[1] heapq.heappush(q,(dist[next[0]],next[0])) print(dist[N]) from collections import defaultdict import heapq N = int(input()) G = defaultdict(list) for i in range(1,N): a,b,x = map(int,input().split()) G[i].append((i+1,a)) G[i].append((x,b)) seen = [False] * (N+1) dist = [10**15] * (N+1) dist[1] = 0 q = [(0,1)] heapq.heapify(q) while(len(q)>0): v = heapq.heappop(q)[1] """ E-TrainではこれをつけてTLE改善 if seen[v] == True: continue """ seen[v] = True for next in G[v]: if not seen[next[0]] and dist[next[0]] > dist[v] + next[1]: dist[next[0]] = dist[v] + next[1] heapq.heappush(q,(dist[next[0]],next[0])) print(dist[N])
ConDefects/ConDefects/Code/abc340_d/Python/55038628
condefects-python_data_2597
n=int(input()) p=[tuple(map(int,input().split())) for i in range(n)] l=[p[i-1]+p[i] for i in range(n)] s=tuple(map(int,input().split())) g=tuple(map(int,input().split())) p+=[s] p+=[g] p.sort() def calc(a,c,b): ax,ay=a bx,by=b cx,cy=c return (ax-cx)*(by-cy)-(ay-cy)*(bx-cx) c1=[] for i in range(len(p)): while len(c1)>=2 and calc(p[i],c1[-1],c1[-2])>=0: c1.pop() c1+=[p[i]] c2=[] for i in range(len(p)): while len(c2)>=2 and calc(p[i],c2[-1],c2[-2])<=0: c2.pop() c2+=[p[i]] def dist(a,b): ax,ay=a bx,by=b return ((ax-bx)**2+(ay-by)**2)**0.5 c=c1[:len(c1)-1]+c2[::-1] if (c not in s) or (c not in g): print(dist(s,g)) exit() d=[0]*len(c) for i in range(len(c)-1): p1=c[i] p2=c[i+1] d[i]=dist(p1,p2) d[i]+=d[i-1] l=min(c.index(s),c.index(g)) r=max(c.index(s),c.index(g)) print(min(d[-2]-d[r-1]+d[l-1],d[r-1]-d[l-1])) n=int(input()) p=[tuple(map(int,input().split())) for i in range(n)] l=[p[i-1]+p[i] for i in range(n)] s=tuple(map(int,input().split())) g=tuple(map(int,input().split())) p+=[s] p+=[g] p.sort() def calc(a,c,b): ax,ay=a bx,by=b cx,cy=c return (ax-cx)*(by-cy)-(ay-cy)*(bx-cx) c1=[] for i in range(len(p)): while len(c1)>=2 and calc(p[i],c1[-1],c1[-2])>=0: c1.pop() c1+=[p[i]] c2=[] for i in range(len(p)): while len(c2)>=2 and calc(p[i],c2[-1],c2[-2])<=0: c2.pop() c2+=[p[i]] def dist(a,b): ax,ay=a bx,by=b return ((ax-bx)**2+(ay-by)**2)**0.5 c=c1[:len(c1)-1]+c2[::-1] if (s not in c) or (g not in c): print(dist(s,g)) exit() d=[0]*len(c) for i in range(len(c)-1): p1=c[i] p2=c[i+1] d[i]=dist(p1,p2) d[i]+=d[i-1] l=min(c.index(s),c.index(g)) r=max(c.index(s),c.index(g)) print(min(d[-2]-d[r-1]+d[l-1],d[r-1]-d[l-1]))
ConDefects/ConDefects/Code/abc286_h/Python/46785855
condefects-python_data_2598
def resolve(): import sys input = sys.stdin.readline MOD = 998244353 INF = float("inf") n = int(input()) points = [tuple(map(int, input().split())) for _ in range(n)] s = tuple(map(int, input().split())) t = tuple(map(int, input().split())) edges = [[] for _ in range(n + 2)] is_direct = True for i in range(n): j = (i + 1) % n d = distance(points[j], points[i]) edges[i].append((j, d)) edges[j].append((i, d)) for i in range(-1, n - 1): if not intersect(s, points[i], points[i - 1], points[i + 1]): edges[n].append((i % n, distance(s, points[i]))) if not intersect(t, points[i], points[i - 1], points[i + 1]): edges[i % n].append((n + 1, distance(t, points[i]))) if is_direct and intersect_seg(s, t, points[i - 1], points[i]): is_direct = False if is_direct: print(distance(s, t)) return import heapq q = [(0.0, n)] reached = [False] * (n + 2) while q: d, i = heapq.heappop(q) if reached[i]: continue if i == n + 1: print(d) return reached[i] = True for j, k in edges[i]: if reached[j]: continue heapq.heappush(q, (d + k, j)) def distance(a, b) -> float: # 2点間のユークリッド距離 return sum((i - j) ** 2 for i, j in zip(a, b)) ** 0.5 def intersect(p1, p2, p3, p4): # 直線p1p2と線分p3p4が重なっているか判定 tc1 = (p1[0] - p2[0]) * (p3[1] - p1[1]) + (p1[1] - p2[1]) * (p1[0] - p3[0]) tc2 = (p1[0] - p2[0]) * (p4[1] - p1[1]) + (p1[1] - p2[1]) * (p1[0] - p4[0]) td1 = (p3[0] - p4[0]) * (p1[1] - p3[1]) + (p3[1] - p4[1]) * (p3[0] - p1[0]) td2 = (p3[0] - p4[0]) * (p2[1] - p3[1]) + (p3[1] - p4[1]) * (p3[0] - p2[0]) return tc1 * tc2 < 0 and td1 * td2 < 0 def intersect_seg(p1, p2, p3, p4): # 線分p1p2と線分p3p4が重なっているか判定 return intersect(p1, p2, p3, p4) and intersect(p3, p4, p1, p2) if __name__ == "__main__": resolve() def resolve(): import sys input = sys.stdin.readline MOD = 998244353 INF = float("inf") n = int(input()) points = [tuple(map(int, input().split())) for _ in range(n)] s = tuple(map(int, input().split())) t = tuple(map(int, input().split())) edges = [[] for _ in range(n + 2)] is_direct = True for i in range(n): j = (i + 1) % n d = distance(points[j], points[i]) edges[i].append((j, d)) edges[j].append((i, d)) for i in range(-1, n - 1): if not intersect(s, points[i], points[i - 1], points[i + 1]): edges[n].append((i % n, distance(s, points[i]))) if not intersect(t, points[i], points[i - 1], points[i + 1]): edges[i % n].append((n + 1, distance(t, points[i]))) if is_direct and intersect_seg(s, t, points[i - 1], points[i]): is_direct = False if is_direct: print(distance(s, t)) return import heapq q = [(0.0, n)] reached = [False] * (n + 2) while q: d, i = heapq.heappop(q) if reached[i]: continue if i == n + 1: print(d) return reached[i] = True for j, k in edges[i]: if reached[j]: continue heapq.heappush(q, (d + k, j)) def distance(a, b) -> float: # 2点間のユークリッド距離 return sum((i - j) ** 2 for i, j in zip(a, b)) ** 0.5 def intersect(p1, p2, p3, p4): # 直線p1p2と線分p3p4が重なっているか判定 tc1 = (p1[0] - p2[0]) * (p3[1] - p1[1]) + (p1[1] - p2[1]) * (p1[0] - p3[0]) tc2 = (p1[0] - p2[0]) * (p4[1] - p1[1]) + (p1[1] - p2[1]) * (p1[0] - p4[0]) td1 = (p3[0] - p4[0]) * (p1[1] - p3[1]) + (p3[1] - p4[1]) * (p3[0] - p1[0]) td2 = (p3[0] - p4[0]) * (p2[1] - p3[1]) + (p3[1] - p4[1]) * (p3[0] - p2[0]) return tc1 * tc2 <= 0 and td1 * td2 <= 0 def intersect_seg(p1, p2, p3, p4): # 線分p1p2と線分p3p4が重なっているか判定 return intersect(p1, p2, p3, p4) and intersect(p3, p4, p1, p2) if __name__ == "__main__": resolve()
ConDefects/ConDefects/Code/abc286_h/Python/38346885
condefects-python_data_2599
print("ABCDEFGHIJKLMNOPQRSTUVWZ"[:int(input())]) print("ABCDEFGHIJKLMNOPQRSTUVWXYZ"[:int(input())])
ConDefects/ConDefects/Code/abc282_a/Python/45264195
condefects-python_data_2600
k = input() a = "ABCDEFG" s = a[:int(k)] print(s) k = input() a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" s = a[:int(k)] print(s)
ConDefects/ConDefects/Code/abc282_a/Python/45920464