import sys readline=sys.stdin.readline class Path_Doubling: def __init__(self,N,permutation,lst=None,f=None,e=None): self.N=N self.permutation=permutation self.lst=lst self.f=f self.e=e def Build_Next(self,K): self.K=K self.k=self.K.bit_length() self.permutation_doubling=[[self.permutation[n]] for n in range(self.N)] self.doubling=[[self.lst[n]] for n in range(self.N)] for k in range(1,self.k): for n in range(self.N): self.permutation_doubling[n].append(self.permutation_doubling[self.permutation_doubling[n][k-1]][k-1]) self.doubling[n].append(self.f(self.doubling[n][k-1],self.doubling[self.permutation_doubling[n][k-1]][k-1])) def Permutation_Doubling(self,N,K): for k in range(self.k): if K>>k&1: N=self.permutation_doubling[N][k] return N def Doubling(self,N,K): retu=self.e for k in range(self.k): if K>>k&1: retu=self.f(retu,self.doubling[N][k]) N=self.permutation_doubling[N][k] return N,retu def Bisect(self,x,is_ok): if not is_ok(x): return -1,None K=0 for k in range(self.k-1,-1,-1): if K|1<