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..= 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() ######################## 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,ox,oy) = get().split().map(parseInt).unpack(4) L = newSeqWith(N,get().strip().split().map(parseInt)).transpose() proc isOasis(x,y:int) :bool = x == ox-1 and y == oy-1 # use dp as closed var closed = newSeqWith(N,newSeqWith(N,[false,false])) var opens = newBinaryHeap[tuple[x,y,used,v:int]]( proc(a,b:tuple[x,y,used,v:int]): int = - a.v + b.v ) opens.push((0,0,false.int,V)) proc dijkstra():void = while opens.size() > 0: let (x,y,used,v) = opens.pop() if closed[x][y][used] : continue closed[x][y][used] = true #echo((x:x,y:y,u:used,v:v)) 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_used = used n_v = v - L[nx][ny] if n_v <= 0 : continue if isOasis(nx,ny) and (not used.bool): n_used = true.int n_v *= 2 if not closed[nx][ny][n_used]: opens.push((nx,ny,n_used,n_v)) if nx == N-1 and ny == N-1: echo "YES" quit() dijkstra() echo "NO" #[ ########### DP ########################### var dp = newSeqWith(N,newSeqWith(N,[OPEN,OPEN])) proc dp_seek(x,y,used:int): void = if x == N-1 and y == N-1: echo "YES" quit() 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_used = used v = dp[x][y][used] - L[nx][ny] if isOasis(nx,ny) and (not used.bool): n_used = true.int v *= 2 if dp[nx][ny][n_used] < v and v > 0: dp[nx][ny][n_used] = v dp_seek(nx,ny,n_used) dp_seek(0,0,false.int) echo "NO" ]#