(H,W),*AB = $<.map{|ln| ln.split.map(&:to_i) }

rmin,r = 0,(1..W).map{|c| [0,c] }
AB.each.with_index(1){|(a,b),k|
	i = (0...r.size).bsearch{|i| a<=r[i][1] }||r.size
	j = (i...r.size).bsearch{|j| b< r[j][1] }||r.size
	u = r[j] && b+1 == r[j][1] ? j : j-1 if i<j && b<W
	v = r[u][0] + b+1 - r[u][1] if u

	r[i...j] = v ? [[v,b+1]] : []
	rmin, = r.min_by{|v,| v == rmin ? (break v) : (next v) } || -k-1

	p k+rmin
}
