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);
  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::Semigroup;
    use std::collections::vec_deque::{self, VecDeque};
    use std::fmt::{self, Debug, Formatter};
    use std::iter::FromIterator;

    pub struct AggregatableDeque<S: Semigroup> {
      buf: VecDeque<Chunk<S::Underlying>>,
      mid: usize,
    }

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

    impl<S: Semigroup> AggregatableDeque<S> {
      pub fn new() -> Self {
        AggregatableDeque {
          buf: VecDeque::new(),
          mid: 0,
        }
      }

      pub fn with_capacity(capacity: usize) -> Self {
        AggregatableDeque {
          buf: VecDeque::with_capacity(capacity),
          mid: 0,
        }
      }

      pub fn iter(&self) -> Iter<S> {
        Iter(self.buf.iter())
      }

      pub fn len(&self) -> usize {
        self.buf.len()
      }

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

      pub fn clear(&mut self) {
        self.buf.clear();
        self.mid = 0;
      }

      pub fn front(&self) -> Option<&S::Underlying> {
        self.buf.front().map(|chunk| &chunk.value)
      }

      pub fn back(&self) -> Option<&S::Underlying> {
        self.buf.back().map(|chunk| &chunk.value)
      }

      pub fn pop_front(&mut self) -> Option<S::Underlying> {
        loop {
          if self.is_empty() {
            return None;
          } else if let Some(chunk) = self.buf_pop_front() {
            return Some(chunk.value);
          } else {
            self.mid = self.buf.len() / 2 + self.buf.len() % 2;
            self.recalc();
          }
        }
      }

      pub fn pop_back(&mut self) -> Option<S::Underlying> {
        loop {
          if self.is_empty() {
            return None;
          } else if let Some(chunk) = self.buf_pop_back() {
            return Some(chunk.value);
          } else {
            self.mid = self.buf.len() / 2;
            self.recalc();
          }
        }
      }

      pub fn push_front(&mut self, value: S::Underlying) {
        let sum = self.buf_front().map_or_else(|| value.clone(), |chunk| S::op(&value, &chunk.sum));
        self.buf_push_front(Chunk { value: value, sum: sum });
      }

      pub fn push_back(&mut self, value: S::Underlying) {
        let sum = self.buf_back().map_or_else(|| value.clone(), |chunk| S::op(&chunk.sum, &value));
        self.buf_push_back(Chunk { value: value, sum: sum })
      }

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

      fn buf_front(&self) -> Option<&Chunk<S::Underlying>> {
        if self.mid > 0 {
          self.buf.front()
        } else {
          None
        }
      }

      fn buf_back(&self) -> Option<&Chunk<S::Underlying>> {
        if self.mid < self.buf.len() {
          self.buf.back()
        } else {
          None
        }
      }

      fn buf_pop_front(&mut self) -> Option<Chunk<S::Underlying>> {
        if self.mid > 0 {
          self.mid -= 1;
          self.buf.pop_front()
        } else {
          None
        }
      }

      fn buf_pop_back(&mut self) -> Option<Chunk<S::Underlying>> {
        if self.mid < self.buf.len() {
          self.buf.pop_back()
        } else {
          None
        }
      }

      fn buf_push_front(&mut self, chunk: Chunk<S::Underlying>) {
        self.mid += 1;
        self.buf.push_front(chunk);
      }

      fn buf_push_back(&mut self, chunk: Chunk<S::Underlying>) {
        self.buf.push_back(chunk);
      }

      fn recalc(&mut self) {
        if self.mid > 0 {
          self.buf[self.mid - 1].sum = self.buf[self.mid - 1].value.clone();
          for i in (0..self.mid - 1).rev() {
            self.buf[i].sum = S::op(&self.buf[i].value, &self.buf[i + 1].sum);
          }
        }
        if self.mid < self.buf.len() {
          self.buf[self.mid].sum = self.buf[self.mid].value.clone();
          for i in self.mid + 1..self.buf.len() {
            self.buf[i].sum = S::op(&self.buf[i - 1].sum, &self.buf[i].value);
          }
        }
      }
    }

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

    impl<S: Semigroup> Debug for AggregatableDeque<S>
    where
      S::Underlying: Debug,
    {
      fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "[ ")?;
        for (i, chunk) in self.buf.iter().enumerate() {
          if i == self.mid {
            write!(f, "| ")?;
          }
          write!(f, "{:?}, ", chunk)?;
        }
        if self.is_empty() || self.mid == self.len() {
          write!(f, "| ")?;
        }
        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.buf.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.buf.into_iter())
      }
    }

    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(iter.size_hint().0);
        for value in iter {
          deque.push_back(value);
        }
        deque
      }
    }

    pub struct Iter<'a, S: 'a + Semigroup>(vec_deque::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>(vec_deque::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> {}
  }
}