eval"N,K,*A="+$<.read.split*?, x,y=0,N*K A.reduce{x,y=[x+K,y+K,(z=_2-_1)>0?z+x:x].min,[x+K,y+K,z<0?y-z:y].min;_2} p x