import sequtils # import algorithm,math,tables # import times,macros,queues,bitops,strutils,intsets,sets # import rationals,critbits,ropes,nre,pegs,complex,stats,heapqueue,sugar template times*(n:int,body) = (for _ in 0.." ,discardable.} proc scan(): int = while true: let k = getchar_unlocked() if k < '0': return result = 10 * result + k.ord - '0'.ord import sequtils,math type ValWithIndex[T] = tuple[val:T,index:int] SegmentTreeWithIndex[T] = ref object data:seq[ValWithIndex[T]] n : int rawSize:int infinity: T cmp:proc(x,y:ValWithIndex[T]):ValWithIndex[T] proc newSegmentTree[T](size:int) : SegmentTreeWithIndex[T] = new(result) result.infinity = 1e12.T proc minimpl[T](x,y:ValWithIndex[T]): ValWithIndex[T] = if x.val <= y.val: x else: y result.cmp = minimpl result.n = size.nextPowerOfTwo() result.rawSize = size result.data = newSeqWith(result.n * 2,(result.infinity,-1)) proc `[]=`[T](self:var SegmentTreeWithIndex[T],i:int,val:T) = let baseI = i var i = i + self.n - 1 self.data[i] = (val,baseI) while i > 0: i = (i - 1) shr 1 self.data[i] = self.cmp(self.data[i * 2 + 1],self.data[i * 2 + 2]) proc queryImpl[T](self:SegmentTreeWithIndex[T],a,b,k,l,r:int) : ValWithIndex[T] = if r <= a or b <= l : return (self.infinity,-1) if a <= l and r <= b : return self.data[k] let vl = self.queryImpl(a,b,k*2+1,l,(l+r) shr 1) let vr = self.queryImpl(a,b,k*2+2,(l+r) shr 1,r) return self.cmp(vl,vr) proc `[]`[T](self:SegmentTreeWithIndex[T],slice:Slice[int]): ValWithIndex[T] = return self.queryImpl(slice.a,slice.b+1,0,0,self.n) proc `$`[T](self:SegmentTreeWithIndex[T]): string = var arrs : seq[seq[ValWithIndex[T]]] = @[] var l = 0 var r = 1 while r <= self.data.len: arrs.add self.data[l..