結果

問題 No.9 モンスターのレベル上げ
ユーザー くれちーくれちー
提出日時 2018-08-09 00:59:34
言語 Rust
(1.77.0 + proconio)
結果
CE  
(最新)
AC  
(最初)
実行時間 -
コード長 10,910 bytes
コンパイル時間 12,927 ms
コンパイル使用メモリ 392,836 KB
最終ジャッジ日時 2024-11-14 20:34:58
合計ジャッジ時間 13,633 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
コンパイルエラー時のメッセージ・ソースコードは、提出者また管理者しか表示できないようにしております。(リジャッジ後のコンパイルエラーは公開されます)
ただし、clay言語の場合は開発者のデバッグのため、公開されます。

コンパイルメッセージ
error[E0432]: unresolved import `io`
   --> src/main.rs:287:9
    |
287 |     use io::FromBytes;
    |         ^^ help: a similar path exists: `crate::io`
    |
    = note: `use` statements changed in Rust 2018; read more at <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-clarity.html>

error[E0432]: unresolved import `misc`
   --> src/main.rs:374:9
    |
374 |     use misc::{ByteChar, ByteString};
    |         ^^^^ help: a similar path exists: `crate::misc`
    |
    = note: `use` statements changed in Rust 2018; read more at <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-clarity.html>

error[E0432]: unresolved import `misc`
   --> src/main.rs:446:9
    |
446 |     use misc::ByteChar;
    |         ^^^^ help: a similar path exists: `crate::misc`
    |
    = note: `use` statements changed in Rust 2018; read more at <https://doc.rust-lang.org/edition-guide/rust-2018/module-system/path-clarity.html>

For more information about this error, try `rustc --explain E0432`.
error: could not compile `main` (bin "main") due to 3 previous errors

ソースコード

diff #

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
    }};
    ($($i:tt : $T:ty),+; $n:expr) => {{
      let mut vecs = ($(Vec::with_capacity({ $i; $n })),+);
      for _ in 0..$n {$(
        vecs.$i.push(scan!($T));
      )+}
      vecs
    }};
  }

  #[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 cmp::{OrdAssign, Reverse};
  use data_structures::SkewHeap;

  let n = scan!(usize);
  let a = scan!(i32; n);
  let b = scan!(i32; n);

  let mut pq = SkewHeap::new();
  let mut ans = i32::max_value();

  for i in 0..n {
    let mut cnt_max = 0;
    pq.extend(a.iter().map(|&a_i| Reverse((a_i, 0))));
    for j in 0..n {
      let k = if i + j >= n { i + j - n } else { i + j };
      let Reverse((x, cnt)) = pq.pop().unwrap();
      cnt_max.max_assign(cnt + 1);
      pq.push(Reverse((x + b[k] / 2, cnt + 1)));
    }
    ans.min_assign(cnt_max);
    pq.clear();
  }

  println!("{}", ans);
}

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 cmp {
  pub use self::ord_assign::*;
  pub use self::reverse::*;

  mod ord_assign {
    pub trait OrdAssign: Sized + Ord {
      fn min_assign(&mut self, other: Self) {
        if other <= *self {
          *self = other;
        }
      }

      fn max_assign(&mut self, other: Self) {
        if other >= *self {
          *self = other
        };
      }
    }

    impl<T: Ord> OrdAssign for T {}
  }

  mod reverse {
    use std::cmp::Ordering;

    #[derive(Clone, Copy, PartialEq, Eq, Default, Debug, Hash)]
    pub struct Reverse<T>(pub T);

    impl<T: PartialOrd> PartialOrd for Reverse<T> {
      fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        other.0.partial_cmp(&self.0)
      }
    }

    impl<T: Ord> Ord for Reverse<T> {
      fn cmp(&self, other: &Self) -> Ordering {
        other.0.cmp(&self.0)
      }
    }
  }
}

pub mod data_structures {
  pub use self::skew_heap::SkewHeap;

  mod skew_heap {
    use std::mem;

    #[derive(Debug, Clone)]
    pub struct SkewHeap<T> {
      root: Link<T>,
      len: usize,
    }

    impl<T: Ord> SkewHeap<T> {
      pub fn new() -> Self {
        SkewHeap { root: None, len: 0 }
      }

      pub fn peek(&self) -> Option<&T> {
        self.root.as_ref().map(|node| &node.value)
      }

      pub fn pop(&mut self) -> Option<T> {
        self.root.take().map(|mut node| {
          self.root = Node::meld(node.left.take(), node.right.take());
          self.len -= 1;
          node.value
        })
      }

      pub fn push(&mut self, value: T) {
        self.root = Node::meld(self.root.take(), Some(Box::new(Node::singleton(value))));
        self.len += 1;
      }

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

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

      pub fn clear(&mut self) {
        self.root.take();
        self.len = 0;
      }

      pub fn append(&mut self, other: &mut Self) {
        self.root = Node::meld(self.root.take(), other.root.take());
        self.len += other.len;
        other.len = 0;
      }
    }

    impl<T: Ord> Extend<T> for SkewHeap<T> {
      fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        for elem in iter {
          self.push(elem);
        }
      }
    }

    #[derive(Debug, Clone)]
    struct Node<T> {
      value: T,
      left: Link<T>,
      right: Link<T>,
    }

    type Link<T> = Option<Box<Node<T>>>;

    impl<T: Ord> Node<T> {
      fn singleton(value: T) -> Self {
        Node {
          value: value,
          left: None,
          right: None,
        }
      }

      fn meld(left: Link<T>, right: Link<T>) -> Link<T> {
        match (left, right) {
          (a, None) => a,
          (None, b) => b,
          (Some(mut a), Some(mut b)) => {
            if a.value < b.value {
              mem::swap(&mut a, &mut b);
            }
            a.right = Self::meld(a.right.take(), Some(b));
            a.swap_children();
            Some(a)
          }
        }
      }

      fn swap_children(&mut self) {
        mem::swap(&mut self.left, &mut self.right);
      }
    }
  }
}

pub mod io {
  pub use self::from_bytes::*;
  pub use self::scanner::*;

  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> {}
  }

  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)
      }
    }
  }
}

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(())
      }
    }
  }
}
0