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 Rust (judge verdict: Accepted)

macro_rules! impl_magma {
  ($T:ty, $U:ty, | $op_lhs:pat, $op_rhs:pat | $op_ret:expr) => {
    impl $crate::math::algebra::Magma for $T {
      type Underlying = $U;

      fn op($op_lhs: &Self::Underlying, $op_rhs: &Self::Underlying) -> Self::Underlying {
        $op_ret
      }
    }
  };
}

macro_rules! impl_identity {
  ($T:ty, $id:expr) => {
    impl $crate::math::algebra::Identity for $T {
      fn identity() -> Self::Underlying {
        $id
      }
    }
  };
}

macro_rules! impl_associative {
  ($T:ty) => {
    impl $crate::math::algebra::Associative for $T {}
  };
}

macro_rules! impl_commutative {
  ($T:ty) => {
    impl $crate::math::algebra::Commutative for $T {}
  };
}

fn solve<R: BufRead, W: Write>(_reader: R, _writer: &mut W) {
  let mut _scanner = Scanner::new(_reader);

  #[allow(unused_macros)]
  macro_rules! scan {
    ($T:ty) => {
      _scanner.next::<$T>().unwrap()
    };
    ($($T:ty),+) => {
      ($(scan!($T)),+)
    };
    ($T:ty; $n:expr $(; $m:expr)*) => {{
      let mut vec = Vec::with_capacity($n);
      for _ in 0..$n {
        vec.push(scan!($T $(; $m)*));
      }
      vec
    }};
  }

  #[allow(unused_macros)]
  macro_rules! scan_iter {
    ($T:ty; $n:expr) => {
      _scanner.take::<$T>($n).map(|x| x.unwrap())
    };
  }

  #[allow(unused_macros)]
  macro_rules! print {
    ($fmt:expr) => {
      write!(_writer, $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      write!(_writer, $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! println {
    ($fmt:expr) => {
      writeln!(_writer, $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      writeln!(_writer, $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! eprint {
    ($fmt:expr) => {
      #[cfg(debug_assertions)]
      write!(::std::io::stderr(), $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      #[cfg(debug_assertions)]
      write!(::std::io::stderr(), $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! eprintln {
    ($fmt:expr) => {
      #[cfg(debug_assertions)]
      writeln!(::std::io::stderr(), $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      #[cfg(debug_assertions)]
      writeln!(::std::io::stderr(), $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! dump {
    ($($x:expr),+) => {
      eprint!("[{}:{}] ", file!(), line!());
      eprintln!(concat!($(stringify!($x), " = {:?}; "),+), $($x),+);
    };
  }

  use data_structures::AggregatableDeque;
  use math::algebra::MinMonoid;

  let (n, l) = scan!(usize, usize);
  let mut a = scan_iter!(u32; n);

  let mut deque = AggregatableDeque::<MinMonoid<u32>>::with_capacity(l, l);
  deque.extend(a.by_ref().take(l));

  print!("{}", deque.aggregate().unwrap());

  for a_i in a {
    deque.pop_front();
    deque.push_back(a_i);
    print!(" {}", deque.aggregate().unwrap());
  }

  println!("");
}

const STACK_SIZE_MEBIBYTES: Option<usize> = None;

fn main() {
  fn run_solver() {
    let stdin = stdin();
    let stdout = stdout();
    #[cfg(debug_assertions)]
    let mut writer = stdout.lock();
    #[cfg(not(debug_assertions))]
    let mut writer = ::std::io::BufWriter::new(stdout.lock());
    solve(stdin.lock(), &mut writer);
    writer.flush().unwrap();
  }
  if let Some(size) = STACK_SIZE_MEBIBYTES {
    let builder = thread::Builder::new().name("solve".to_string()).stack_size(size * 1024 * 1024);
    builder.spawn(run_solver).unwrap().join().unwrap();
  } else {
    run_solver();
  }
}

use io::Scanner;
use std::io::{stdin, stdout, BufRead, Write};
use std::thread;

pub mod math {
  pub mod algebra {
    pub use self::associative::*;
    pub use self::commutative::*;
    pub use self::identity::*;
    pub use self::magma::*;
    pub use self::min_monoid::*;
    pub use self::monoid::*;
    pub use self::semigroup::*;

    mod magma {
      pub trait Magma {
        type Underlying: Clone;

        fn op(lhs: &Self::Underlying, rhs: &Self::Underlying) -> Self::Underlying;

        fn op_assign(lhs: &mut Self::Underlying, rhs: &Self::Underlying) {
          *lhs = Self::op(lhs, rhs);
        }
      }
    }

    mod identity {
      use math::algebra::Magma;

      pub trait Identity: Magma {
        fn identity() -> Self::Underlying;

        fn prop(a: &Self::Underlying) -> bool
        where
          Self::Underlying: PartialEq,
        {
          Self::op(&Self::identity(), a) == *a && Self::op(a, &Self::identity()) == *a
        }
      }
    }

    mod associative {
      use math::algebra::Magma;

      pub trait Associative: Magma {
        fn prop(a: &Self::Underlying, b: &Self::Underlying, c: &Self::Underlying) -> bool
        where
          Self::Underlying: Eq,
        {
          Self::op(&Self::op(a, b), c) == Self::op(a, &Self::op(b, c))
        }
      }
    }

    mod commutative {
      use math::algebra::Magma;

      pub trait Commutative: Magma {
        fn prop(a: &Self::Underlying, b: &Self::Underlying) -> bool
        where
          Self::Underlying: Eq,
        {
          Self::op(a, b) == Self::op(b, a)
        }
      }
    }

    mod semigroup {
      use math::algebra::{Associative, Magma};

      pub trait Semigroup: Magma + Associative {}

      impl<T: Magma + Associative> Semigroup for T {}
    }

    #[macro_use]
    mod monoid {
      use math::algebra::{Associative, Identity, Magma};

      pub trait Monoid: Magma + Associative + Identity {}

      impl<T: Magma + Associative + Identity> Monoid for T {}

      macro_rules! impl_monoid {
        ($t:ty, $u:ty, | $op_l:pat, $op_r:pat | $op_b:expr, $id:expr) => {
          impl_magma! { $t, $u, | $op_l, $op_r | $op_b }
          impl_associative! { $t }
          impl_identity! { $t, $id }
        };
      }
    }

    mod min_monoid {
      #[allow(unused_imports)]
      use math::algebra::{Commutative, Monoid};
      use std::cmp;
      use std::marker::PhantomData;

      pub struct MinMonoid<T: Ord> {
        _marker: PhantomData<fn() -> T>,
      }

      macro_rules! min_monoid_impl {
        ($($t:ty)+) => {$(
          impl_monoid! { MinMonoid<$t>, $t, |&lhs, &rhs| cmp::min(lhs, rhs), <$t>::max_value() }
          impl_commutative! { MinMonoid<$t> }
        )+};
      }

      min_monoid_impl! { i32 i64 isize u8 u32 u64 usize }
    }
  }
}

pub mod misc {
  pub use self::byte_char::*;
  pub use self::byte_string::*;

  mod byte_char {
    use std::fmt::{Debug, Display, Error, Formatter};

    #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
    pub struct ByteChar(pub u8);

    impl Debug for ByteChar {
      fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        write!(f, "b\'{}\'", self.0 as char)
      }
    }

    impl Display for ByteChar {
      fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        write!(f, "{}", self.0 as char)
      }
    }
  }

  mod byte_string {
    use misc::ByteChar;
    use std::fmt::{Debug, Display, Error, Formatter};

    #[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
    pub struct ByteString(pub Vec<ByteChar>);

    impl Debug for ByteString {
      fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        write!(f, "b\"")?;
        for &c in &self.0 {
          write!(f, "{}", c.0 as char)?;
        }
        write!(f, "b\"")
      }
    }

    impl Display for ByteString {
      fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        for &c in &self.0 {
          write!(f, "{}", c.0 as char)?;
        }
        Ok(())
      }
    }
  }
}

pub mod data_structures {
  pub use self::aggregatable_deque::AggregatableDeque;

  mod aggregatable_deque {
    use math::algebra::{Magma, Semigroup};
    use std::fmt::{self, Debug, Formatter};
    use std::iter::{self, FromIterator};
    use std::slice;
    use std::vec;

    type InnerVec<S> = Vec<Chunk<<S as Magma>::Underlying>>;

    pub struct AggregatableDeque<S: Semigroup> {
      front: InnerVec<S>,
      back: InnerVec<S>,
    }

    #[derive(Debug, Clone)]
    struct Chunk<T> {
      value: T,
      sum: T,
    }

    impl<S: Semigroup> AggregatableDeque<S> {
      pub fn new() -> Self {
        AggregatableDeque {
          front: vec![],
          back: vec![],
        }
      }

      pub fn with_capacity(front_capacity: usize, back_capacity: usize) -> Self {
        AggregatableDeque {
          front: Vec::with_capacity(front_capacity),
          back: Vec::with_capacity(back_capacity),
        }
      }

      pub fn iter(&self) -> Iter<S> {
        Iter(self.front.iter().chain(self.back.iter()))
      }

      pub fn len(&self) -> usize {
        self.front.len() + self.back.len()
      }

      pub fn is_empty(&self) -> bool {
        self.front.is_empty() && self.back.is_empty()
      }

      pub fn clear(&mut self) {
        self.front.clear();
        self.back.clear();
      }

      pub fn front(&self) -> Option<&S::Underlying> {
        Self::peek(&self.front)
      }

      pub fn back(&self) -> Option<&S::Underlying> {
        Self::peek(&self.back)
      }

      pub fn pop_front(&mut self) -> Option<S::Underlying> {
        Self::pop(&mut self.front, &mut self.back)
      }

      pub fn pop_back(&mut self) -> Option<S::Underlying> {
        Self::pop(&mut self.back, &mut self.front)
      }

      pub fn push_front(&mut self, value: S::Underlying) {
        Self::push(&mut self.front, value)
      }

      pub fn push_back(&mut self, value: S::Underlying) {
        Self::push(&mut self.back, value)
      }

      pub fn aggregate(&self) -> Option<S::Underlying> {
        match (self.front.last(), self.back.last()) {
          (Some(ref front), Some(ref back)) => Some(S::op(&front.sum, &back.sum)),
          (Some(ref chunk), None) | (None, Some(ref chunk)) => Some(chunk.sum.clone()),
          (None, None) => None,
        }
      }

      fn push(vec: &mut InnerVec<S>, value: S::Underlying) {
        let sum = vec.last().map_or_else(|| value.clone(), |chunk| S::op(&value, &chunk.sum));
        vec.push(Chunk { value: value, sum: sum });
      }

      fn peek(vec: &Vec<Chunk<S::Underlying>>) -> Option<&S::Underlying> {
        vec.last().map(|chunk| &chunk.value)
      }

      fn pop(vec: &mut InnerVec<S>, opposite_vec: &mut InnerVec<S>) -> Option<S::Underlying> {
        loop {
          if let Some(chunk) = vec.pop() {
            return Some(chunk.value);
          } else if opposite_vec.is_empty() {
            return None;
          } else {
            let new_len = opposite_vec.len() / 2 + opposite_vec.len() % 2;
            vec.extend(opposite_vec.drain(..new_len).rev());
            Self::recalc(vec, opposite_vec);
          }
        }
      }

      fn recalc(vec: &mut InnerVec<S>, opposite_vec: &mut InnerVec<S>) {
        if !vec.is_empty() {
          vec[0].sum = vec[0].value.clone();
          for i in 1..vec.len() {
            vec[i].sum = S::op(&vec[i].value, &vec[i - 1].sum);
          }
        }
        if !opposite_vec.is_empty() {
          opposite_vec[0].sum = opposite_vec[0].value.clone();
          for i in 1..opposite_vec.len() {
            opposite_vec[i].sum = S::op(&opposite_vec[i - 1].sum, &opposite_vec[i].value);
          }
        }
      }
    }

    impl<S: Semigroup> Clone for AggregatableDeque<S> {
      fn clone(&self) -> Self {
        AggregatableDeque {
          front: self.front.clone(),
          back: self.back.clone(),
        }
      }
    }

    impl<S: Semigroup> Debug for AggregatableDeque<S>
    where
      S::Underlying: Debug,
    {
      fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "[ ")?;
        for chunk in self.front.iter() {
          write!(f, "{:?}, ", chunk)?;
        }
        write!(f, "| ")?;
        for chunk in self.back.iter() {
          write!(f, "{:?}, ", chunk)?;
        }
        write!(f, "]")
      }
    }

    impl<S: Semigroup> Extend<S::Underlying> for AggregatableDeque<S> {
      fn extend<I: IntoIterator<Item = S::Underlying>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        self.back.reserve(iter.size_hint().0);
        for value in iter {
          self.push_back(value);
        }
      }
    }

    impl<S: Semigroup> IntoIterator for AggregatableDeque<S> {
      type Item = S::Underlying;
      type IntoIter = IntoIter<S>;

      fn into_iter(self) -> Self::IntoIter {
        IntoIter(self.front.into_iter().chain(self.back))
      }
    }

    impl<S: Semigroup> FromIterator<S::Underlying> for AggregatableDeque<S> {
      fn from_iter<I: IntoIterator<Item = S::Underlying>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let mut deque = AggregatableDeque::with_capacity(0, iter.size_hint().0);
        for value in iter {
          deque.push_back(value);
        }
        deque
      }
    }

    type Chain<T> = iter::Chain<T, T>;

    pub struct Iter<'a, S: 'a + Semigroup>(Chain<slice::Iter<'a, Chunk<S::Underlying>>>);

    impl<'a, S: 'a + Semigroup> Iterator for Iter<'a, S> {
      type Item = &'a S::Underlying;

      fn next(&mut self) -> Option<&'a S::Underlying> {
        self.0.next().map(|chunk| &chunk.value)
      }

      fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
      }
    }

    pub struct IntoIter<S: Semigroup>(Chain<vec::IntoIter<Chunk<S::Underlying>>>);

    impl<S: Semigroup> Iterator for IntoIter<S> {
      type Item = S::Underlying;

      fn next(&mut self) -> Option<S::Underlying> {
        self.0.next().map(|chunk| chunk.value)
      }

      fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
      }
    }
  }
}

pub mod io {
  pub use self::from_bytes::FromBytes;
  pub use self::scanner::Scanner;

  mod from_bytes {
    use misc::{ByteChar, ByteString};
    use std::str;
    use std::str::FromStr;

    #[derive(Debug)]
    pub struct FromBytesError;

    pub trait FromBytes: Sized {
      type Err;

      fn from_bytes(bytes: &[u8]) -> Result<Self, Self::Err>;
    }

    impl FromBytes for ByteChar {
      type Err = FromBytesError;

      fn from_bytes(bytes: &[u8]) -> Result<Self, Self::Err> {
        if bytes.len() == 1 {
          Ok(ByteChar(*unsafe { bytes.get_unchecked(0) }))
        } else {
          Err(FromBytesError)
        }
      }
    }

    impl FromBytes for ByteString {
      type Err = FromBytesError;

      fn from_bytes(bytes: &[u8]) -> Result<Self, Self::Err> {
        Ok(ByteString(bytes.iter().cloned().map(ByteChar).collect()))
      }
    }

    impl<T: FromStr> FromBytes for T {
      type Err = T::Err;

      fn from_bytes(bytes: &[u8]) -> Result<Self, Self::Err> {
        let s = if cfg!(debug_assertions) {
          str::from_utf8(bytes).unwrap()
        } else {
          unsafe { str::from_utf8_unchecked(bytes) }
        };
        T::from_str(s)
      }
    }
  }

  mod scanner {
    use io::FromBytes;
    use std::io::BufRead;
    use std::marker::PhantomData;

    pub struct Scanner<R> {
      reader: R,
      buffer: Vec<u8>,
      position: usize,
    }

    impl<R: BufRead> Scanner<R> {
      pub fn new(reader: R) -> Self {
        Scanner {
          reader: reader,
          buffer: vec![],
          position: 0,
        }
      }

      pub fn next<T: FromBytes>(&mut self) -> Result<T, T::Err> {
        FromBytes::from_bytes(self.next_bytes().unwrap_or(&[]))
      }

      pub fn take<T: FromBytes>(&mut self, n: usize) -> Take<R, T> {
        Take {
          scanner: self,
          n: n,
          _marker: PhantomData,
        }
      }

      pub fn next_bytes(&mut self) -> Option<&[u8]> {
        if self.buffer.is_empty() {
          self.read_line();
        }
        loop {
          match self.buffer.get(self.position) {
            Some(&b' ') => self.position += 1,
            Some(&b'\n') => self.read_line(),
            Some(_) => break,
            None => return None,
          }
        }
        let start = self.position;
        loop {
          match self.buffer.get(self.position) {
            Some(&b' ') | Some(&b'\n') | None => break,
            Some(_) => self.position += 1,
          }
        }
        Some(&self.buffer[start..self.position])
      }

      fn read_line(&mut self) {
        self.position = 0;
        self.buffer.clear();
        self.reader.read_until(b'\n', &mut self.buffer).unwrap();
      }
    }

    pub struct Take<'a, R: 'a, T> {
      scanner: &'a mut Scanner<R>,
      n: usize,
      _marker: PhantomData<fn() -> T>,
    }

    impl<'a, R: BufRead, T: FromBytes> Iterator for Take<'a, R, T> {
      type Item = Result<T, T::Err>;

      fn next(&mut self) -> Option<Self::Item> {
        if self.n > 0 {
          self.n -= 1;
          Some(self.scanner.next())
        } else {
          None
        }
      }

      fn size_hint(&self) -> (usize, Option<usize>) {
        (self.n, Some(self.n))
      }
    }

    impl<'a, R: BufRead, T: FromBytes> ExactSizeIterator for Take<'a, R, T> {}
  }
}