Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Sliding Minimum Element

For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $L$, find the minimum of each possible sub-arrays with size $L$ and print them from the beginning. For example, for an array $\{1, 7, 7, 4, 8, 1, 6\}$ and $L = 3$, the possible sub-arrays with size $L = 3$ includes $\{1, 7, 7\}$, $\{7, 7, 4\}$, $\{7, 4, 8\}$, $\{4, 8, 1\}$, $\{8, 1, 6\}$ and the minimum of each sub-array is 1, 4, 4, 1, 1 respectively.

Constraints

$1 \leq N \leq 10^6$

$1 \leq L \leq 10^6$

$1 \leq a_i \leq 10^9$

$L \leq N$

Input

The input is given in the following format.

$N$ $L$

$a_1$ $a_2$ ... $a_N$

Output

Print a sequence of the minimum in a line. Print a space character between adjacent elements.

Sample Input 1

7 3
1 7 7 4 8 1 6

Sample Output 1

1 4 4 1 1

Solution in Ruby (judge verdict: Accepted)

MAX = 2**31-1

def rmq(a, b, k, l, r, node)
  return MAX if r <= a || b <= l
  return node[k] if a <= l && r <= b
  m = (l+r)/2
  vl = rmq(a, b, 2*k+1, l, m, node)
  vr = rmq(a, b, 2*k+2, m, r, node)
  return vl < vr ? vl : vr
end

n, len = gets.split.map(&:to_i)
m = 1
while m < n
  m *= 2
end
node = Array.new(2*m-1){MAX}
arr = gets.split.map(&:to_i)


monotonically_increase = true
arr.size.times{|i|
  monotonically_increase = false if i > 0 && arr[i]-arr[i-1] < 0
  k = i + m - 1
  node[k] = arr[i]
  while k > 0
    k = (k-1)/2
    node[k] = node[2*k+1] < node[2*k+2] ? node[2*k+1] : node[2*k+2]
  end
}

if monotonically_increase
  puts arr[0..-len].join(" ")
  exit
end

pos = {}
len.times{|i|
  pos[arr[i]] = i
}
i = len
j = 0

min = rmq(j, i, 0, 0, m, node)
idx = pos[min]

print min

loop do
  break if i >= n

  pos[arr[i]] = i
  pos.delete(arr[j]) if pos[arr[j]] == j

  if min >= arr[i] then
    min = arr[i]
    idx = i
  elsif idx == j then # drop out minimum number from the window
    min = rmq(j+1, i+1, 0, 0, m, node)
    idx = pos[min]
  end
  print " #{min}"
  i += 1
  j += 1
end

puts