import sequtils,strutils,strscans,algorithm,math,future,sets,queues,tables,macros macro unpack*(rhs: seq,cnt: static[int]): auto = let t = genSym(); result = quote do:(let `t` = `rhs`;()) for i in 0.. int): BinaryHeap[T] = BinaryHeap[T](nodes:newSeq[T](),compare:compare,popchunk:false) proc compareNode[T](h:BinaryHeap[T],i,j:int):int = h.compare(h.nodes[i],h.nodes[j]) proc size*[T](h:BinaryHeap[T]):int = h.nodes.len() - h.popchunk.int proc items*[T](h:var BinaryHeap[T]):seq[T] = if h.popchunk : discard h.popimpl() return h.nodes proc top*[T](h:var BinaryHeap[T]): T = if h.popchunk : discard h.popimpl() return h.nodes[0] proc push*[T](h:var BinaryHeap[T],node:T):void = if h.popchunk : h.nodes[0] = node h.shiftdown() else: h.pushimpl(node) proc pop*[T](h:var BinaryHeap[T]):T = if h.popchunk: discard h.popimpl() h.popchunk = true return h.nodes[0] proc shiftdown[T](h:var BinaryHeap[T]): void = h.popchunk = false let size = h.nodes.len() var i = 0 while true : let L = i * 2 + 1 let R = i * 2 + 2 if L >= size : break let child = if R < size and h.compareNode(R,L) <= 0 : R else: L if h.compareNode(i,child) <= 0: break swap(h.nodes[i],h.nodes[child]) i = child proc pushimpl[T](h:var BinaryHeap[T],node:T):void = h.nodes.add(node) #末尾に追加 var i = h.nodes.len() - 1 while i > 0: # 末尾から木を整形 let parent = (i - 1) div 2 if h.compare(h.nodes[parent],node) <= 0: break h.nodes[i] = h.nodes[parent] i = parent h.nodes[i] = node proc popimpl[T](h:var BinaryHeap[T]):T = result = h.nodes[0] # rootと末尾を入れ替えて木を整形 h.nodes[0] = h.nodes[^1] h.nodes.setLen(h.nodes.len() - 1) h.shiftdown() # TODO: pqueue shl shr # TODO: pqueue ######################## Binary Heap ############################# # 0以下で死亡 / V - Lxy => Oasis(v *= 2,once) # N <= 200, V <= 500, Lxy <= 9 # x:N * y:N * use:2 => V # 最短でゴール or 最短でオアシス +最短でゴールのみ let (N,V,oax,oay) = get().split().map(parseInt).unpack(4) L = newSeqWith(N,get().strip().split().map(parseInt)).transpose() (ox,oy) = (oax-1,oay-1) proc twoFactorDijkestra(sx,sy,sv:int,checkOasis:bool = true):void = type field = tuple[x,y,v:int] var closed = newSeqWith(N,newSeqWith(N,false)) var opens = newBinaryHeap[field]( proc(a,b:field): int = -a.v + b.v) opens.push((sx,sy,sv)) while opens.size() > 0: let (x,y,v) = opens.pop() if closed[x][y] : continue closed[x][y] = true if checkOasis and x == ox and y == oy: twoFactorDijkestra(x,y,v * 2,false) continue for d in dxdy4: let (nx,ny) = (d.x + x,d.y + y) if nx < 0 or ny < 0 or nx >= N or ny >= N : continue var n_v = v - L[nx][ny] if n_v <= 0 : continue if not closed[nx][ny]: opens.push((nx,ny,n_v)) if nx == N-1 and ny == N-1: echo "YES" quit() twoFactorDijkestra(0,0,V) echo "NO"