import strutils, sequtils, algorithm, future, tables, sets type PrirorityQueue*[T] = ref object of RootObj elms: seq[T] idxs: TableRef[T, int] cmp: (T, T) -> int proc newPriorityQueue*[T](cmp: (T, T) -> int): PrirorityQueue[T] = new(result) result.elms = newSeq[T]() result.idxs = newTable[T, int]() result.cmp = cmp template parent(cur: int): int = (cur - 1) div 2 template childl(cur: int): int = cur * 2 + 1 template childr(cur: int): int = cur * 2 + 2 proc innerDel[T](self: var PrirorityQueue[T], cur: int) = self.idxs.del(self.elms[cur]) self.elms.del(cur) proc innerSwap[T](self: var PrirorityQueue[T], s, t: int) = let (sval, tval) = (self.elms[s], self.elms[t]) swap(self.elms[s], self.elms[t]) swap(self.idxs[sval], self.idxs[tval]) proc upHeap[T](self: var PrirorityQueue[T], cur: var int) = var par = parent(cur) while par >= 0 and self.cmp(self.elms[cur], self.elms[par]) < 0: self.innerSwap(cur, par) (cur, par) = (par, parent(par)) proc downHeap[T](self: var PrirorityQueue[T], cur: var int) = var (chl, chr) = (childl(cur), childr(cur)) while chl < self.elms.len: var ch = if chr >= self.elms.len or self.cmp(self.elms[chl], self.elms[chr]) < 0: chl else: chr if self.cmp(self.elms[cur], self.elms[ch]) < 0: break self.innerSwap(cur, ch) (cur, chl, chr) = (ch, childl(cur), childr(cur)) proc len*[T](self: PrirorityQueue[T]): int = assert self.elms.len == self.idxs.len self.elms.len proc push*[T](self: var PrirorityQueue[T], data: T): bool {.discardable.} = if self.idxs.contains(data): return false var n = self.elms.len cur = n self.elms.setLen(n + 1) self.elms[cur] = data self.idxs[data] = cur self.upHeap(cur) return true proc peek*[T](self: var PrirorityQueue[T]): T = self.elms[0] proc pop*[T](self: var PrirorityQueue[T]): T = assert self.elms.len > 0 var n = self.elms.len cur = 0 result = self.elms[0] self.innerSwap(0, n-1) self.innerDel(n-1) self.downHeap(cur) proc del*[T](self: var PrirorityQueue[T], data: T) = if not self.idxs.contains(data): return let n = self.elms.len var idx = self.idxs[data] if idx == n - 1: self.innerDel(n-1) else: self.innerSwap(idx, n-1) self.innerDel(n-1) self.downHeap(idx) self.upHeap(idx) # ============================================================================== when isMainModule: var n = stdin.readLine.parseInt a = stdin.readLine.split.map(parseInt) b = newSeq[int](n) lastIdx = newTable[int, int]() pQ = newPriorityQueue[int]((x: int, y: int) => y - x) for i in 0..