提出 #33363906


ソースコード 拡げる

pub mod solution {
//{"name":"E - Pairing Wizards","group":"AtCoder - AtCoder Regular Contest 142","url":"https://atcoder.jp/contests/arc142/tasks/arc142_e","interactive":false,"timeLimit":2000,"tests":[{"input":"5\n1 5\n2 4\n3 3\n4 2\n5 1\n3\n1 4\n2 5\n3 5\n","output":"2\n"},{"input":"4\n1 1\n1 1\n1 1\n1 1\n3\n1 2\n2 3\n3 4\n","output":"0\n"},{"input":"9\n1 1\n2 4\n5 5\n7 10\n9 3\n9 13\n10 9\n3 9\n2 9\n7\n1 5\n2 5\n1 6\n2 4\n3 4\n4 9\n8 9\n","output":"22\n"}],"testType":"single","input":{"type":"stdin","fileName":null,"pattern":null},"output":{"type":"stdout","fileName":null,"pattern":null},"languages":{"java":{"taskClass":"EPairingWizards"}}}

use std::cmp::max;
use std::cmp::min;
use std::time::Instant;

use crate::algo_lib::graph::compressed_graph::CompressedGraph;
use crate::algo_lib::graph::edges::edge_trait::EdgeTrait;
use crate::algo_lib::graph::edges::simple_edge::SimpleEdge;
use crate::algo_lib::graph::edges::weighted_edge::WeightedEdge;
use crate::algo_lib::graph::graph_builder::GraphBuilder;
use crate::algo_lib::graph::graph_readers::config::Directional;
use crate::algo_lib::graph::graph_readers::config::Indexation;
use crate::algo_lib::graph::graph_readers::simple::read_graph;
use crate::algo_lib::graph::graph_trait::GraphTrait;
use crate::algo_lib::io::output::output;
use crate::algo_lib::io::task_io_settings::TaskIoType;
use crate::algo_lib::io::task_runner::run_task;
use crate::algo_lib::io::input::Input;
use crate::algo_lib::io::task_io_settings::TaskIoSettings;
use crate::algo_lib::misc::gen_vector::gen_vec;
use crate::algo_lib::misc::min_max::UpdateMinMax;
use crate::algo_lib::misc::rand::Random;
#[allow(unused)]
use crate::dbg;
use crate::out;
use crate::out_line;

// Just a multiset of integers, with fast [max] and [second_max]
#[derive(Clone, Debug)]
struct Requirements {
    cnt: Vec<usize>,
    mask: u128,
    max_iter: usize,
}

impl Requirements {
    const MASK_MAX: usize = 110;

    pub fn new(max_val: usize) -> Self {
        Self {
            cnt: vec![0; max_val + 1],
            mask: 0,
            max_iter: 0,
        }
    }

    pub fn add(&mut self, pos: usize) {
        self.cnt[pos] += 1;
        self.max_iter.update_max(pos);
        self.mask |= 1u128 << (Self::MASK_MAX - pos);
    }

    pub fn remove(&mut self, pos: usize) {
        self.cnt[pos] -= 1;
        if self.cnt[pos] == 0 {
            self.mask ^= 1u128 << (Self::MASK_MAX - pos);
            self.max_iter = Self::MASK_MAX - self.mask.trailing_zeros() as usize;
        }
    }

    pub fn second_max(&self) -> usize {
        if self.cnt[self.max_iter] == 1 {
            let new_mask = self.mask ^ (1u128 << (Self::MASK_MAX - self.max_iter));
            Self::MASK_MAX - new_mask.trailing_zeros() as usize
        } else {
            self.max_iter
        }
    }
}

// Some heuristic to get probably better initial permutation than just totally random
fn gen_initial_ranks(rnd: &mut Random, start: &[usize], need: &[usize]) -> Vec<usize> {
    let n = start.len();

    let mx = rnd.gen(10..200i32);
    let a = rnd.gen(-mx..mx);
    let b = rnd.gen(-mx..mx);
    let mut scores = gen_vec(n, |pos| {
        (
            pos,
            start[pos] as i32 * a + need[pos] as i32 * b + rnd.gen(0..mx * mx),
        )
    });
    scores.sort_by_key(|(_, y)| *y);
    let mut ranks = vec![0; n];
    for i in 0..n {
        ranks[scores[i].0] = i;
    }
    ranks
}

fn remove_rank(ranks: &mut [usize], rank: usize) {
    for x in ranks.iter_mut() {
        if *x > rank {
            *x -= 1;
        }
    }
}

fn insert_rank(
    ranks: &mut [usize],
    elem: usize,
    new_rank: usize,
    g: &CompressedGraph<WeightedEdge<usize>>,
    requirements: &mut [Requirements],
) {
    let old_rank = ranks[elem];
    for x in ranks.iter_mut() {
        if *x >= new_rank {
            *x += 1;
        }
    }
    ranks[elem] = new_rank;

    let (from_rank, to_rank) = if old_rank < new_rank {
        (old_rank, new_rank)
    } else {
        (new_rank + 1, old_rank + 1)
    };

    for e in g.adj(elem) {
        if ranks[e.to()] < from_rank || ranks[e.to()] >= to_rank {
            continue;
        }
        if ranks[elem] < ranks[e.to()] {
            requirements[e.to()].remove(e.cost);
            requirements[elem].add(e.cost);
        } else {
            requirements[elem].remove(e.cost);
            requirements[e.to()].add(e.cost);
        }
    }
}

fn push_suffix_max(a: &mut [usize]) {
    let mut mx = 0;
    for x in a.iter_mut().rev() {
        mx.update_max(*x);
        *x = mx;
    }
}

fn push_prefix_sum(a: &mut [usize]) {
    let mut add = 0;
    for x in a.iter_mut() {
        add += *x;
        *x = add;
    }
}

fn run_local_optimizations(
    start: &[usize],
    need: &[usize],
    rnd: &mut Random,
    g: &CompressedGraph<WeightedEdge<usize>>,
) -> usize {
    let n = need.len();

    let max_val = *need.iter().chain(start.iter()).max().unwrap();
    let mut requirements = vec![Requirements::new(max_val); n];
    for v in 0..n {
        for _ in 0..n + 1 {
            requirements[v].add(start[v]);
        }
    }
    // we maintain property:
    // if rank[i] < rank[j], and we have edge i-j, than:
    // value[i] >= max(need[i], need[j])
    // value[j] >= min(need[i], need[j])
    let mut ranks = gen_initial_ranks(rnd, &start, &need);
    for (fr, e) in g.all_edges() {
        if ranks[fr] < ranks[e.to()] {
            requirements[fr].add(e.cost);
        }
    }

    let calc_score =
        |requirements: &[Requirements]| -> usize { requirements.iter().map(|r| r.max_iter).sum() };

    let mut best_res = calc_score(&requirements);
    loop {
        let mut found_improvement = false;
        for elem in rnd.gen_permutation(n).into_iter() {
            // if we set rank[elem] = x (and move others),
            // we will need to set value[elem] to value_should_be_at_least[x], and
            // increase other values in total by additional_cost[x]
            let mut value_should_be_at_least = vec![start[elem]; n];
            let mut additional_cost = vec![0; n];

            let old_rank = ranks[elem];
            remove_rank(&mut ranks, old_rank);

            for e in g.adj(elem) {
                let req_without = if ranks[elem] <= ranks[e.to()] {
                    requirements[e.to()].max_iter
                } else {
                    requirements[e.to()].second_max()
                };
                additional_cost[ranks[e.to()] + 1] = if e.cost > req_without {
                    e.cost - req_without
                } else {
                    0
                };
            }
            for e in g.adj(elem) {
                value_should_be_at_least[ranks[e.to()]] = e.cost;
            }
            push_suffix_max(&mut value_should_be_at_least);
            push_prefix_sum(&mut additional_cost);

            let best_new_rank = value_should_be_at_least
                .iter()
                .zip(additional_cost.iter())
                .map(|(x, y)| x + y)
                .enumerate()
                .min_by_key(|(_, snd)| *snd)
                .unwrap()
                .0;

            insert_rank(&mut ranks, elem, best_new_rank, g, &mut requirements);
            let new_res = calc_score(&requirements);
            assert!(new_res <= best_res);
            if best_res > new_res {
                found_improvement = true;
            }
            best_res = new_res;
        }
        if !found_improvement {
            break;
        }
    }
    best_res
}

fn solve_case(start: &[usize], need: &[usize], g: &CompressedGraph<SimpleEdge>) -> usize {
    let mut start = start.to_vec();
    let n = start.len();
    let sum_start = start.iter().sum::<usize>();
    for v in 0..n {
        for e in g.adj(v) {
            start[v].update_max(min(need[v], need[e.to()]));
        }
    }
    let mut g_weighted = GraphBuilder::new(n);
    for (fr, e) in g.all_edges() {
        g_weighted.add_edge(fr, WeightedEdge::new(e.to(), max(need[fr], need[e.to()])));
    }
    let g_weighted = g_weighted.build();

    let mut rnd = Random::new(787788);
    let mut best_res = std::usize::MAX;
    let start_time = Instant::now();
    while start_time.elapsed().as_millis() < 500 {
        best_res.update_min(run_local_optimizations(
            &start,
            &need,
            &mut rnd,
            &g_weighted,
        ));
    }
    best_res - sum_start
}

fn solve(input: &mut Input) {
    let n = input.usize();
    let mut start = vec![0; n];
    let mut need = vec![0; n];
    for i in 0..n {
        start[i] = input.usize() - 1;
        need[i] = input.usize() - 1;
    }
    let num_edges = input.usize();
    let g = read_graph(
        input,
        n,
        num_edges,
        Directional::Undirected,
        Indexation::FromOne,
    );
    let res = solve_case(&start, &need, &g);
    out_line!(res);
}

pub(crate) fn run(mut input: Input) -> bool {
    solve(&mut input);
    output().flush();
    input.skip_whitespace();
    input.peek().is_none()
}

#[allow(unused)]
pub fn submit() -> bool {
    let io = TaskIoSettings {
        is_interactive: false,
        input: TaskIoType::Std,
        output: TaskIoType::Std,
    };

    run_task(io, run)
}

}
pub mod algo_lib {
pub mod collections {
pub mod array_2d {
use crate::algo_lib::io::output::Output;
use crate::algo_lib::io::output::Writable;
use crate::algo_lib::misc::num_traits::Number;
use std::io::Write;
use std::ops::Index;
use std::ops::IndexMut;
use std::ops::Mul;

// TODO: implement good Debug
#[derive(Clone, Debug)]
pub struct Array2D<T> {
    rows: usize,
    cols: usize,
    v: Vec<T>,
}

pub struct Iter<'a, T> {
    array: &'a Array2D<T>,
    row: usize,
    col: usize,
}

impl<T> Array2D<T>
where
    T: Clone,
{
    #[allow(unused)]
    pub fn new(empty: T, rows: usize, cols: usize) -> Self {
        Self {
            rows,
            cols,
            v: vec![empty; rows * cols],
        }
    }

    pub fn new_f(rows: usize, cols: usize, mut f: impl FnMut(usize, usize) -> T) -> Self {
        let mut v = Vec::with_capacity(rows * cols);
        for r in 0..rows {
            for c in 0..cols {
                v.push(f(r, c));
            }
        }
        Self { rows, cols, v }
    }

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

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

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

    pub fn swap(&mut self, row1: usize, row2: usize) {
        assert!(row1 < self.rows);
        assert!(row2 < self.rows);
        if row1 != row2 {
            for col in 0..self.cols {
                self.v.swap(row1 * self.cols + col, row2 * self.cols + col);
            }
        }
    }

    pub fn transpose(&self) -> Self {
        Self::new_f(self.cols, self.rows, |r, c| self[c][r].clone())
    }

    pub fn iter(&self) -> Iter<T> {
        Iter {
            array: self,
            row: 0,
            col: 0,
        }
    }

    pub fn pref_sum(&self) -> Self
    where
        T: Number,
    {
        let mut res = Self::new(T::ZERO, self.rows + 1, self.cols + 1);
        for i in 0..self.rows {
            for j in 0..self.cols {
                let value = self[i][j] + res[i][j + 1] + res[i + 1][j] - res[i][j];
                res[i + 1][j + 1] = value;
            }
        }
        res
    }
}

impl<T> Writable for Array2D<T>
where
    T: Writable,
{
    fn write(&self, output: &mut Output) {
        for r in 0..self.rows {
            self[r].write(output);
            output.write(&[b'\n']).unwrap();
        }
    }
}

impl<T> Index<usize> for Array2D<T> {
    type Output = [T];

    fn index(&self, index: usize) -> &Self::Output {
        &self.v[(index) * self.cols..(index + 1) * self.cols]
    }
}

impl<T> IndexMut<usize> for Array2D<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.v[(index) * self.cols..(index + 1) * self.cols]
    }
}

impl<T> Mul for &Array2D<T>
where
    T: Number,
{
    type Output = Array2D<T>;

    fn mul(self, rhs: Self) -> Self::Output {
        let n = self.rows;
        let m = self.cols;
        assert_eq!(m, rhs.rows);
        let k2 = rhs.cols;
        let mut res = Array2D::new(T::ZERO, n, k2);
        for i in 0..n {
            for j in 0..m {
                for k in 0..k2 {
                    res[i][k] += self[i][j] * rhs[j][k];
                }
            }
        }
        res
    }
}

impl<T> Array2D<T>
where
    T: Number,
{
    pub fn pown(&self, pw: usize) -> Self {
        assert_eq!(self.rows, self.cols);
        let n = self.rows;
        if pw == 0 {
            Self::new_f(n, n, |r, c| if r == c { T::ONE } else { T::ZERO })
        } else if pw == 1 {
            self.clone()
        } else {
            let half = self.pown(pw / 2);
            let half2 = &half * &half;
            if pw & 1 == 0 {
                half2
            } else {
                &half2 * &self
            }
        }
    }
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.col == self.array.cols {
            self.col = 0;
            self.row += 1;
        }
        if self.row >= self.array.rows {
            return None;
        }
        let elem = &self.array[self.row][self.col];
        self.col += 1;
        Some(elem)
    }
}
}
}
pub mod graph {
pub mod compressed_graph {
use crate::algo_lib::graph::edges::edge_trait::EdgeTrait;
use crate::algo_lib::graph::graph_trait::GraphTrait;

#[derive(Clone)]
pub struct CompressedGraph<E>
where
    E: EdgeTrait,
{
    num_vertices: usize,
    edges: Vec<E>,
    start_of_edges: Vec<u32>,
}

impl<E> CompressedGraph<E>
where
    E: EdgeTrait,
    E: Default,
{
    pub fn with_edge_iter<Iter>(num_vertices: usize, edge_iter: Iter) -> Self
    where
        Iter: Iterator<Item = (usize, E)> + Clone,
    {
        let mut num_of_edges: Vec<u32> = vec![0u32; num_vertices + 1];
        for (fr, _edge) in edge_iter.clone() {
            num_of_edges[fr] += 1;
        }
        let mut start_of_edges = num_of_edges;
        for i in 1..=num_vertices {
            start_of_edges[i] += start_of_edges[i - 1];
        }
        let mut edges = vec![E::default(); start_of_edges[num_vertices] as usize];
        for (fr, edge) in edge_iter {
            start_of_edges[fr] -= 1;
            edges[start_of_edges[fr] as usize] = edge;
        }
        Self {
            num_vertices,
            edges,
            start_of_edges,
        }
    }
}

impl<E> GraphTrait<E> for CompressedGraph<E>
where
    E: EdgeTrait,
{
    fn len(&self) -> usize {
        self.num_vertices
    }

    fn num_vertices(&self) -> usize {
        self.num_vertices
    }

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

    #[inline(always)]
    fn adj(&self, v: usize) -> &[E] {
        let from = self.start_of_edges[v] as usize;
        let to = self.start_of_edges[v + 1] as usize;
        &self.edges[from..to]
    }
}

impl<E> CompressedGraph<E>
where
    E: EdgeTrait,
{
    pub fn all_edges(&self) -> impl Iterator<Item = (usize, &E)> + '_ {
        (0..self.num_vertices()).flat_map(move |v| self.adj(v).iter().map(move |e| (v, e)))
    }
}
}
pub mod edges {
pub mod edge_trait {
pub trait EdgeTrait: Copy + Clone {
    fn to(&self) -> usize;
    fn rev(&self, from: usize) -> Self;
}
}
pub mod simple_edge {
use crate::algo_lib::graph::edges::edge_trait::EdgeTrait;

#[derive(Copy, Clone, Default)]
pub struct SimpleEdge {
    to: u32,
}

impl SimpleEdge {
    pub fn new(to: usize) -> Self {
        Self { to: to as u32 }
    }
}

impl EdgeTrait for SimpleEdge {
    #[inline(always)]
    fn to(&self) -> usize {
        self.to as usize
    }

    fn rev(&self, from: usize) -> Self {
        Self { to: from as u32 }
    }
}
}
pub mod weighted_edge {
use crate::algo_lib::graph::edges::edge_trait::EdgeTrait;
use crate::algo_lib::misc::num_traits::Number;

#[derive(Copy, Clone, Default)]
pub struct WeightedEdge<T>
where
    T: Number,
{
    to: u32,
    pub cost: T,
}

impl<T> WeightedEdge<T>
where
    T: Number,
{
    pub fn new(to: usize, cost: T) -> Self {
        Self {
            to: to as u32,
            cost,
        }
    }
}

impl<T> EdgeTrait for WeightedEdge<T>
where
    T: Number,
{
    #[inline(always)]
    fn to(&self) -> usize {
        self.to as usize
    }

    fn rev(&self, from: usize) -> Self {
        Self {
            to: from as u32,
            cost: self.cost,
        }
    }
}
}
}
pub mod graph_builder {
use crate::algo_lib::graph::compressed_graph::CompressedGraph;
use crate::algo_lib::graph::edges::edge_trait::EdgeTrait;

pub struct GraphBuilder<E>
where
    E: EdgeTrait,
{
    num_vertices: usize,
    edges: Vec<(u32, E)>,
}

impl<E> GraphBuilder<E>
where
    E: EdgeTrait,
    E: Default,
{
    pub fn new(num_vertices: usize) -> Self {
        Self {
            num_vertices,
            edges: vec![],
        }
    }

    pub fn add_vertex(&mut self) {
        self.num_vertices += 1;
    }

    pub fn add_edge(&mut self, from: usize, edge: E) {
        self.edges.push((from as u32, edge));
    }

    pub fn build(self) -> CompressedGraph<E> {
        CompressedGraph::with_edge_iter(
            self.num_vertices,
            self.edges.iter().map(|(fr, edge)| (*fr as usize, *edge)),
        )
    }
}
}
pub mod graph_readers {
pub mod config {
pub enum Directional {
    Directed,
    Undirected,
}

pub enum Indexation {
    FromZero,
    FromOne,
}
}
pub mod simple {
use crate::algo_lib::graph::compressed_graph::CompressedGraph;
use crate::algo_lib::graph::edges::edge_trait::EdgeTrait;
use crate::algo_lib::graph::edges::simple_edge::SimpleEdge;
use crate::algo_lib::graph::graph_readers::config::*;
use crate::algo_lib::io::input::Input;

fn read_directed_edges(
    input: &mut Input,
    num_edges: usize,
    indexation: Indexation,
) -> Vec<(usize, SimpleEdge)> {
    (0..num_edges)
        .map(|_| {
            let mut read_v = || -> usize {
                match indexation {
                    Indexation::FromZero => input.usize(),
                    Indexation::FromOne => input.usize() - 1,
                }
            };
            let fr = read_v();
            let to = read_v();
            (fr, SimpleEdge::new(to))
        })
        .collect()
}

pub fn read_graph(
    input: &mut Input,
    num_vertices: usize,
    num_edges: usize,
    directional: Directional,
    indexation: Indexation,
) -> CompressedGraph<SimpleEdge> {
    let mut edges = read_directed_edges(input, num_edges, indexation);
    match directional {
        Directional::Directed => (),
        Directional::Undirected => {
            let mut rev_edges: Vec<_> = edges
                .iter()
                .map(|(fr, edge)| (edge.to(), SimpleEdge::new(*fr)))
                .collect();
            edges.append(&mut rev_edges);
        }
    };
    CompressedGraph::with_edge_iter(num_vertices, edges.iter().map(|(fr, edge)| (*fr, *edge)))
}
}
}
pub mod graph_trait {
use crate::algo_lib::graph::edges::edge_trait::EdgeTrait;

pub trait GraphTrait<E>
where
    E: EdgeTrait,
{
    // alias for [num_vertices]
    fn len(&self) -> usize;
    fn num_vertices(&self) -> usize;
    fn num_edges(&self) -> usize;

    fn adj(&self, v: usize) -> &[E];
}
}
}
pub mod io {
pub mod input {
use crate::algo_lib::collections::array_2d::Array2D;
use crate::algo_lib::misc::ord_f64::OrdF64;
use std::fmt::Debug;
use std::io::Read;
use std::marker::PhantomData;
use std::path::Path;
use std::str::FromStr;

pub struct Input {
    input: Box<dyn Read>,
    buf: Vec<u8>,
    at: usize,
    buf_read: usize,
}

macro_rules! read_integer_fun {
    ($t:ident) => {
        #[allow(unused)]
        pub fn $t(&mut self) -> $t {
            self.read_integer()
        }
    };
}

impl Input {
    const DEFAULT_BUF_SIZE: usize = 4096;

    ///
    /// Using with stdin:
    /// ```no_run
    /// use algo_lib::io::input::Input;
    /// let stdin = std::io::stdin();
    /// let input = Input::new(Box::new(stdin));
    /// ```
    ///
    /// For read files use ``new_file`` instead.
    ///
    ///
    pub fn new(input: Box<dyn Read>) -> Self {
        Self {
            input,
            buf: vec![0; Self::DEFAULT_BUF_SIZE],
            at: 0,
            buf_read: 0,
        }
    }

    pub fn new_file<P: AsRef<Path>>(path: P) -> Self {
        let file = std::fs::File::open(&path)
            .unwrap_or_else(|_| panic!("Can't open file: {:?}", path.as_ref().as_os_str()));
        Self::new(Box::new(file))
    }

    pub fn new_with_size(input: Box<dyn Read>, buf_size: usize) -> Self {
        Self {
            input,
            buf: vec![0; buf_size],
            at: 0,
            buf_read: 0,
        }
    }

    pub fn new_file_with_size<P: AsRef<Path>>(path: P, buf_size: usize) -> Self {
        let file = std::fs::File::open(&path)
            .unwrap_or_else(|_| panic!("Can't open file: {:?}", path.as_ref().as_os_str()));
        Self::new_with_size(Box::new(file), buf_size)
    }

    pub fn get(&mut self) -> Option<u8> {
        if self.refill_buffer() {
            let res = self.buf[self.at];
            self.at += 1;
            Some(res)
        } else {
            None
        }
    }

    pub fn peek(&mut self) -> Option<u8> {
        if self.refill_buffer() {
            Some(self.buf[self.at])
        } else {
            None
        }
    }

    pub fn skip_whitespace(&mut self) {
        while let Some(b) = self.peek() {
            if !char::from(b).is_whitespace() {
                return;
            }
            self.get();
        }
    }

    pub fn next_token(&mut self) -> Option<Vec<u8>> {
        self.skip_whitespace();
        let mut res = Vec::new();
        while let Some(c) = self.get() {
            if char::from(c).is_whitespace() {
                break;
            }
            res.push(c);
        }
        if res.is_empty() {
            None
        } else {
            Some(res)
        }
    }

    //noinspection RsSelfConvention
    pub fn is_exhausted(&mut self) -> bool {
        self.peek().is_none()
    }

    pub fn has_more_elements(&mut self) -> bool {
        !self.is_exhausted()
    }

    pub fn read<T: Readable>(&mut self) -> T {
        T::read(self)
    }

    pub fn vec<T: Readable>(&mut self, size: usize) -> Vec<T> {
        let mut res = Vec::with_capacity(size);
        for _ in 0usize..size {
            res.push(self.read());
        }
        res
    }

    pub fn string_vec(&mut self, size: usize) -> Vec<Vec<u8>> {
        let mut res = Vec::with_capacity(size);
        for _ in 0usize..size {
            res.push(self.string());
        }
        res
    }

    pub fn matrix<T: Readable>(&mut self, rows: usize, cols: usize) -> Array2D<T>
    where
        T: Clone,
    {
        Array2D::new_f(rows, cols, |_, _| self.read())
    }

    pub fn read_line(&mut self) -> String {
        let mut res = String::new();
        while let Some(c) = self.get() {
            if c == b'\n' {
                break;
            }
            if c == b'\r' {
                if self.peek() == Some(b'\n') {
                    self.get();
                }
                break;
            }
            res.push(c.into());
        }
        res
    }

    #[allow(clippy::should_implement_trait)]
    pub fn into_iter<T: Readable>(self) -> InputIterator<T> {
        InputIterator {
            input: self,
            phantom: Default::default(),
        }
    }

    fn read_integer<T: FromStr>(&mut self) -> T
    where
        <T as FromStr>::Err: Debug,
    {
        let res = self.read_string();
        res.parse::<T>().unwrap()
    }

    fn read_string(&mut self) -> String {
        match self.next_token() {
            None => {
                panic!("Input exhausted");
            }
            Some(res) => unsafe { String::from_utf8_unchecked(res) },
        }
    }

    pub fn string_as_string(&mut self) -> String {
        self.read_string()
    }

    pub fn string(&mut self) -> Vec<u8> {
        self.read_string().into_bytes()
    }

    fn read_char(&mut self) -> char {
        self.skip_whitespace();
        self.get().unwrap().into()
    }

    fn read_float(&mut self) -> OrdF64 {
        self.read_string().parse().unwrap()
    }

    pub fn f64(&mut self) -> OrdF64 {
        self.read_float()
    }

    fn refill_buffer(&mut self) -> bool {
        if self.at == self.buf_read {
            self.at = 0;
            self.buf_read = self.input.read(&mut self.buf).unwrap();
            self.buf_read != 0
        } else {
            true
        }
    }

    read_integer_fun!(i32);
    read_integer_fun!(i64);
    read_integer_fun!(i128);
    read_integer_fun!(u32);
    read_integer_fun!(u64);
    read_integer_fun!(usize);
}

pub trait Readable {
    fn read(input: &mut Input) -> Self;
}

impl Readable for String {
    fn read(input: &mut Input) -> Self {
        input.read_string()
    }
}

impl Readable for char {
    fn read(input: &mut Input) -> Self {
        input.read_char()
    }
}

impl Readable for f64 {
    fn read(input: &mut Input) -> Self {
        input.read_string().parse().unwrap()
    }
}

impl Readable for f32 {
    fn read(input: &mut Input) -> Self {
        input.read_string().parse().unwrap()
    }
}

impl<T: Readable> Readable for Vec<T> {
    fn read(input: &mut Input) -> Self {
        let size = input.read();
        input.vec(size)
    }
}

pub struct InputIterator<T: Readable> {
    input: Input,
    phantom: PhantomData<T>,
}

impl<T: Readable> Iterator for InputIterator<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.input.skip_whitespace();
        self.input.peek().map(|_| self.input.read())
    }
}

macro_rules! read_integer {
    ($t:ident) => {
        impl Readable for $t {
            fn read(input: &mut Input) -> Self {
                input.read_integer()
            }
        }
    };
}

read_integer!(i8);
read_integer!(i16);
read_integer!(i32);
read_integer!(i64);
read_integer!(i128);
read_integer!(isize);
read_integer!(u8);
read_integer!(u16);
read_integer!(u32);
read_integer!(u64);
read_integer!(u128);
read_integer!(usize);

macro_rules! tuple_readable {
    ( $( $name:ident )+ ) => {
        impl<$($name: Readable), +> Readable for ($($name,)+) {
            fn read(input: &mut Input) -> Self {
                ($($name::read(input),)+)
            }
        }
    }
}

tuple_readable! {T}
tuple_readable! {T U}
tuple_readable! {T U V}
tuple_readable! {T U V X}
tuple_readable! {T U V X Y}
tuple_readable! {T U V X Y Z}
tuple_readable! {T U V X Y Z A}
tuple_readable! {T U V X Y Z A B}
tuple_readable! {T U V X Y Z A B C}
tuple_readable! {T U V X Y Z A B C D}
tuple_readable! {T U V X Y Z A B C D E}
tuple_readable! {T U V X Y Z A B C D E F}
}
pub mod output {
use std::io::Write;

pub struct Output {
    output: Box<dyn Write>,
    buf: Vec<u8>,
    at: usize,
    auto_flush: bool,
}

impl Output {
    const DEFAULT_BUF_SIZE: usize = 4096;

    pub fn new(output: Box<dyn Write>) -> Self {
        Self {
            output,
            buf: vec![0; Self::DEFAULT_BUF_SIZE],
            at: 0,
            auto_flush: false,
        }
    }

    pub fn new_with_auto_flush(output: Box<dyn Write>) -> Self {
        Self {
            output,
            buf: vec![0; Self::DEFAULT_BUF_SIZE],
            at: 0,
            auto_flush: true,
        }
    }

    pub fn flush(&mut self) {
        if self.at != 0 {
            self.output.write_all(&self.buf[..self.at]).unwrap();
            self.at = 0;
            self.output.flush().expect("Couldn't flush output");
        }
    }

    pub fn print<T: Writable>(&mut self, s: &T) {
        s.write(self);
    }

    pub fn put(&mut self, b: u8) {
        self.buf[self.at] = b;
        self.at += 1;
        if self.at == self.buf.len() {
            self.flush();
        }
    }

    pub fn maybe_flush(&mut self) {
        if self.auto_flush {
            self.flush();
        }
    }

    pub fn print_per_line<T: Writable>(&mut self, arg: &[T]) {
        for i in arg {
            i.write(self);
            self.put(b'\n');
        }
    }

    pub fn print_iter<T: Writable, I: Iterator<Item = T>>(&mut self, iter: I) {
        let mut first = true;
        for e in iter {
            if first {
                first = false;
            } else {
                self.put(b' ');
            }
            e.write(self);
        }
    }

    pub fn print_iter_ref<'a, T: 'a + Writable, I: Iterator<Item = &'a T>>(&mut self, iter: I) {
        let mut first = true;
        for e in iter {
            if first {
                first = false;
            } else {
                self.put(b' ');
            }
            e.write(self);
        }
    }
}

impl Write for Output {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let mut start = 0usize;
        let mut rem = buf.len();
        while rem > 0 {
            let len = (self.buf.len() - self.at).min(rem);
            self.buf[self.at..self.at + len].copy_from_slice(&buf[start..start + len]);
            self.at += len;
            if self.at == self.buf.len() {
                self.flush();
            }
            start += len;
            rem -= len;
        }
        if self.auto_flush {
            self.flush();
        }
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.flush();
        Ok(())
    }
}

pub trait Writable {
    fn write(&self, output: &mut Output);
}

impl Writable for &str {
    fn write(&self, output: &mut Output) {
        output.write_all(self.as_bytes()).unwrap();
    }
}

impl Writable for String {
    fn write(&self, output: &mut Output) {
        output.write_all(self.as_bytes()).unwrap();
    }
}

impl Writable for char {
    fn write(&self, output: &mut Output) {
        output.put(*self as u8);
    }
}

impl<T: Writable> Writable for [T] {
    fn write(&self, output: &mut Output) {
        output.print_iter_ref(self.iter());
    }
}

impl<T: Writable> Writable for Vec<T> {
    fn write(&self, output: &mut Output) {
        self[..].write(output);
    }
}

macro_rules! write_to_string {
    ($t:ident) => {
        impl Writable for $t {
            fn write(&self, output: &mut Output) {
                self.to_string().write(output);
            }
        }
    };
}

write_to_string!(u8);
write_to_string!(u16);
write_to_string!(u32);
write_to_string!(u64);
write_to_string!(u128);
write_to_string!(usize);
write_to_string!(i8);
write_to_string!(i16);
write_to_string!(i32);
write_to_string!(i64);
write_to_string!(i128);
write_to_string!(isize);
write_to_string!(f32);
write_to_string!(f64);

impl<T: Writable, U: Writable> Writable for (T, U) {
    fn write(&self, output: &mut Output) {
        self.0.write(output);
        output.put(b' ');
        self.1.write(output);
    }
}

impl<T: Writable, U: Writable, V: Writable> Writable for (T, U, V) {
    fn write(&self, output: &mut Output) {
        self.0.write(output);
        output.put(b' ');
        self.1.write(output);
        output.put(b' ');
        self.2.write(output);
    }
}

pub static mut OUTPUT: Option<Output> = None;

pub fn set_global_output_to_stdout() {
    unsafe {
        OUTPUT = Some(Output::new(Box::new(std::io::stdout())));
    }
}

pub fn set_global_output_to_file(path: &str) {
    unsafe {
        let out_file = std::fs::File::create(path).expect(&format!("Can't create file {}", path));
        OUTPUT = Some(Output::new(Box::new(out_file)));
    }
}

pub fn set_global_output_to_none() {
    unsafe {
        match &mut OUTPUT {
            None => {}
            Some(output) => output.flush(),
        }
        OUTPUT = None;
    }
}

pub fn output() -> &'static mut Output {
    unsafe {
        match &mut OUTPUT {
            None => {
                panic!("Global output wasn't initialized");
            }
            Some(output) => output,
        }
    }
}

#[macro_export]
macro_rules! out {
    ($first: expr $(,$args:expr )*) => {
        output().print(&$first);
        $(output().put(b' ');
        output().print(&$args);
        )*
        output().maybe_flush();
    }
}

#[macro_export]
macro_rules! out_line {
    ($first: expr $(, $args:expr )* ) => {
        {
            out!($first $(,$args)*);
            output().put(b'\n');
            output().maybe_flush();
        }
    };
    () => {
        {
            output().put(b'\n');
            output().maybe_flush();
        }
    };
}
}
pub mod task_io_settings {
pub enum TaskIoType {
    Std,
    File(String),
}

pub struct TaskIoSettings {
    pub is_interactive: bool,
    pub input: TaskIoType,
    pub output: TaskIoType,
}
}
pub mod task_runner {
use std::io::Write;

use super::input::Input;
use super::output::Output;
use super::output::OUTPUT;
use super::task_io_settings::TaskIoSettings;
use super::task_io_settings::TaskIoType;

pub fn run_task<Res>(io: TaskIoSettings, run: impl FnOnce(Input) -> Res) -> Res {
    let output: Box<dyn Write> = match io.output {
        TaskIoType::Std => Box::new(std::io::stdout()),
        TaskIoType::File(file) => {
            let out_file = std::fs::File::create(file).unwrap();
            Box::new(out_file)
        }
    };

    unsafe {
        if io.is_interactive {
            OUTPUT = Some(Output::new_with_auto_flush(output));
        } else {
            OUTPUT = Some(Output::new(output));
        }
    }

    let input = match io.input {
        TaskIoType::Std => {
            let sin = std::io::stdin();
            if io.is_interactive {
                Input::new_with_size(Box::new(sin), 1)
            } else {
                Input::new(Box::new(sin))
            }
        }
        TaskIoType::File(file) => {
            if io.is_interactive {
                Input::new_file_with_size(file, 1)
            } else {
                Input::new_file(file)
            }
        }
    };

    run(input)
}
}
}
pub mod misc {
pub mod dbg_macro {
#[macro_export]
#[allow(unused_macros)]
macro_rules! dbg {
    ($first_val:expr, $($val:expr),+ $(,)?) => {
        eprint!("[{}:{}] {} = {:?}",
                    file!(), line!(), stringify!($first_val), &$first_val);
        ($(eprint!(", {} = {:?}", stringify!($val), &$val)),+,);
        eprintln!();
    };
    ($first_val:expr) => {
        eprintln!("[{}:{}] {} = {:?}",
                    file!(), line!(), stringify!($first_val), &$first_val)
    };
}
}
pub mod gen_vector {
pub fn gen_vec<T>(n: usize, mut f: impl FnMut(usize) -> T) -> Vec<T> {
    (0..n).map(|id| f(id)).collect()
}
}
pub mod min_max {
pub trait UpdateMinMax: PartialOrd + Sized {
    #[inline(always)]
    fn update_min(&mut self, other: Self) -> bool {
        if other < *self {
            *self = other;
            true
        } else {
            false
        }
    }

    #[inline(always)]
    fn update_max(&mut self, other: Self) -> bool {
        if other > *self {
            *self = other;
            true
        } else {
            false
        }
    }
}

impl<T: PartialOrd + Sized> UpdateMinMax for T {}

pub trait FindMinMaxPos {
    fn index_of_min(&self) -> usize;
    fn index_of_max(&self) -> usize;
}

impl<T: PartialOrd> FindMinMaxPos for [T] {
    fn index_of_min(&self) -> usize {
        let mut pos_of_best = 0;
        for (idx, val) in self.iter().enumerate().skip(1) {
            if val < &self[pos_of_best] {
                pos_of_best = idx;
            }
        }
        pos_of_best
    }

    fn index_of_max(&self) -> usize {
        let mut pos_of_best = 0;
        for (idx, val) in self.iter().enumerate().skip(1) {
            if val > &self[pos_of_best] {
                pos_of_best = idx;
            }
        }
        pos_of_best
    }
}

pub fn index_of_min_by<T, F>(n: usize, f: F) -> usize
where
    T: PartialOrd,
    F: Fn(usize) -> T,
{
    assert!(n > 0);
    let mut best_idx = 0;
    let mut best_val = f(0);
    for idx in 1..n {
        let cur_val = f(idx);
        if cur_val < best_val {
            best_val = cur_val;
            best_idx = idx;
        }
    }
    best_idx
}

pub fn index_of_max_by<T, F>(n: usize, f: F) -> usize
where
    T: PartialOrd,
    F: Fn(usize) -> T,
{
    assert!(n > 0);
    let mut best_idx = 0;
    let mut best_val = f(0);
    for idx in 1..n {
        let cur_val = f(idx);
        if cur_val > best_val {
            best_val = cur_val;
            best_idx = idx;
        }
    }
    best_idx
}
}
pub mod num_traits {
use std::fmt::Debug;
use std::ops::Add;
use std::ops::AddAssign;
use std::ops::Div;
use std::ops::DivAssign;
use std::ops::Mul;
use std::ops::MulAssign;
use std::ops::Sub;
use std::ops::SubAssign;

pub trait HasConstants<T> {
    const MAX: T;
    const MIN: T;
    const ZERO: T;
    const ONE: T;
    const TWO: T;
}

pub trait ConvI32<T> {
    fn from_i32(val: i32) -> T;
    fn to_i32(self) -> i32;
}

pub trait Number:
    Copy
    + Add<Output = Self>
    + AddAssign
    + Sub<Output = Self>
    + SubAssign
    + Mul<Output = Self>
    + MulAssign
    + Div<Output = Self>
    + DivAssign
    + Ord
    + PartialOrd
    + Eq
    + PartialEq
    + HasConstants<Self>
    + Default
    + Debug
    + Sized
    + ConvI32<Self>
{
}

impl<
        T: Copy
            + Add<Output = Self>
            + AddAssign
            + Sub<Output = Self>
            + SubAssign
            + Mul<Output = Self>
            + MulAssign
            + Div<Output = Self>
            + DivAssign
            + Ord
            + PartialOrd
            + Eq
            + PartialEq
            + HasConstants<Self>
            + Default
            + Debug
            + Sized
            + ConvI32<Self>,
    > Number for T
{
}

macro_rules! has_constants_impl {
    ($t: ident) => {
        impl HasConstants<$t> for $t {
            // TODO: remove `std` for new rust version..
            const MAX: $t = std::$t::MAX;
            const MIN: $t = std::$t::MIN;
            const ZERO: $t = 0;
            const ONE: $t = 1;
            const TWO: $t = 2;
        }

        impl ConvI32<$t> for $t {
            fn from_i32(val: i32) -> $t {
                val as $t
            }

            fn to_i32(self) -> i32 {
                self as i32
            }
        }
    };
}

has_constants_impl!(i32);
has_constants_impl!(i64);
has_constants_impl!(i128);
has_constants_impl!(u32);
has_constants_impl!(u64);
has_constants_impl!(u128);
has_constants_impl!(usize);
has_constants_impl!(u8);

impl ConvI32<Self> for f64 {
    fn from_i32(val: i32) -> Self {
        val as f64
    }

    fn to_i32(self) -> i32 {
        self as i32
    }
}

impl HasConstants<Self> for f64 {
    const MAX: Self = Self::MAX;
    const MIN: Self = -Self::MAX;
    const ZERO: Self = 0.0;
    const ONE: Self = 1.0;
    const TWO: Self = 2.0;
}
}
pub mod ord_f64 {
use crate::algo_lib::io::input::Input;
use crate::algo_lib::io::input::Readable;
use crate::algo_lib::io::output::Output;
use crate::algo_lib::io::output::Writable;
use crate::algo_lib::misc::num_traits::ConvI32;
use crate::algo_lib::misc::num_traits::HasConstants;
use std::cmp::min;
use std::cmp::Ordering;
use std::f64::consts::PI;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::io::Write;
use std::num::ParseFloatError;
use std::ops::Neg;
use std::ops::Rem;
use std::str::FromStr;

#[derive(PartialOrd, PartialEq, Copy, Clone, Default)]
pub struct OrdF64(pub f64);

impl OrdF64 {
    pub const EPS: Self = Self(1e-9);
    pub const SMALL_EPS: Self = Self(1e-4);
    pub const PI: Self = Self(PI);

    pub fn abs(&self) -> Self {
        Self(self.0.abs())
    }

    pub fn eq_with_eps(&self, other: &Self, eps: Self) -> bool {
        let abs_diff = (*self - *other).abs();
        abs_diff <= eps || abs_diff <= min(self.abs(), other.abs()) * eps
    }

    pub fn eq_with_default_eps(&self, other: &Self) -> bool {
        self.eq_with_eps(other, Self::EPS)
    }

    pub fn sqrt(&self) -> Self {
        Self(self.0.sqrt())
    }

    pub fn powf(&self, n: f64) -> Self {
        Self(self.0.powf(n))
    }
}

impl Eq for OrdF64 {}

impl Ord for OrdF64 {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl std::ops::Add for OrdF64 {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}

impl std::ops::AddAssign for OrdF64 {
    fn add_assign(&mut self, rhs: Self) {
        self.0 += rhs.0;
    }
}

impl std::ops::Sub for OrdF64 {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        Self(self.0 - rhs.0)
    }
}

impl std::ops::SubAssign for OrdF64 {
    fn sub_assign(&mut self, rhs: Self) {
        self.0 -= rhs.0;
    }
}

impl std::ops::Mul for OrdF64 {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self::Output {
        Self(self.0 * rhs.0)
    }
}

impl std::ops::MulAssign for OrdF64 {
    fn mul_assign(&mut self, rhs: Self) {
        self.0 *= rhs.0;
    }
}

impl std::ops::Div for OrdF64 {
    type Output = Self;

    fn div(self, rhs: Self) -> Self::Output {
        Self(self.0 / rhs.0)
    }
}

impl std::ops::DivAssign for OrdF64 {
    fn div_assign(&mut self, rhs: Self) {
        self.0 /= rhs.0;
    }
}

impl Neg for OrdF64 {
    type Output = Self;

    fn neg(self) -> Self::Output {
        Self(-self.0)
    }
}

impl Display for OrdF64 {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl Debug for OrdF64 {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.0, f)
    }
}

impl Writable for OrdF64 {
    fn write(&self, output: &mut Output) {
        output.write_fmt(format_args!("{}", self.0)).unwrap();
    }
}

impl Readable for OrdF64 {
    fn read(input: &mut Input) -> Self {
        Self(input.read::<f64>())
    }
}

impl HasConstants<Self> for OrdF64 {
    const MAX: Self = Self(f64::MAX);
    const MIN: Self = Self(-f64::MAX);
    const ZERO: Self = Self(0.0);
    const ONE: Self = Self(1.0);
    const TWO: Self = Self(2.0);
}

impl ConvI32<Self> for OrdF64 {
    fn from_i32(val: i32) -> Self {
        Self(val as f64)
    }

    fn to_i32(self) -> i32 {
        self.0 as i32
    }
}

impl FromStr for OrdF64 {
    type Err = ParseFloatError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.parse::<f64>() {
            Ok(value) => Ok(Self(value)),
            Err(error) => Err(error),
        }
    }
}

impl From<OrdF64> for f64 {
    fn from(x: OrdF64) -> Self {
        x.0
    }
}

impl Rem for OrdF64 {
    type Output = Self;

    fn rem(self, rhs: Self) -> Self::Output {
        Self(self.0 % rhs.0)
    }
}

#[macro_export]
macro_rules! f {
    ($a:expr) => {
        OrdF64($a)
    };
}

impl From<usize> for OrdF64 {
    fn from(x: usize) -> Self {
        f!(x as f64)
    }
}

impl From<i32> for OrdF64 {
    fn from(x: i32) -> Self {
        f!(x as f64)
    }
}

impl From<i64> for OrdF64 {
    fn from(x: i64) -> Self {
        f!(x as f64)
    }
}

impl From<f64> for OrdF64 {
    fn from(x: f64) -> Self {
        f!(x)
    }
}
}
pub mod rand {
use crate::algo_lib::misc::gen_vector::gen_vec;
use crate::algo_lib::misc::num_traits::Number;
use std::ops::Range;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;

#[allow(dead_code)]
pub struct Random {
    state: u64,
}

impl Random {
    pub fn gen_u64(&mut self) -> u64 {
        let mut x = self.state;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.state = x;
        x
    }

    #[allow(dead_code)]
    pub fn next_in_range(&mut self, from: usize, to: usize) -> usize {
        assert!(from < to);
        (from as u64 + self.gen_u64() % ((to - from) as u64)) as usize
    }

    pub fn gen_index<T>(&mut self, a: &[T]) -> usize {
        self.gen(0..a.len())
    }

    #[allow(dead_code)]
    #[inline(always)]
    pub fn gen_double(&mut self) -> f64 {
        (self.gen_u64() as f64) / (std::usize::MAX as f64)
    }

    #[allow(dead_code)]
    pub fn new(seed: u64) -> Self {
        let state = if seed == 0 { 787788 } else { seed };
        Self { state }
    }

    pub fn new_time_seed() -> Self {
        let time = SystemTime::now();
        let seed = (time.duration_since(UNIX_EPOCH).unwrap().as_nanos() % 1_000_000_000) as u64;
        if seed == 0 {
            Self::new(787788)
        } else {
            Self::new(seed)
        }
    }

    #[allow(dead_code)]
    pub fn gen_permutation(&mut self, n: usize) -> Vec<usize> {
        let mut result: Vec<_> = (0..n).collect();
        for i in 0..n {
            let idx = self.next_in_range(0, i + 1);
            result.swap(i, idx);
        }
        result
    }

    pub fn gen<T>(&mut self, range: Range<T>) -> T
    where
        T: Number,
    {
        let from = T::to_i32(range.start);
        let to = T::to_i32(range.end);
        assert!(from < to);
        let len = (to - from) as usize;
        T::from_i32(self.next_in_range(0, len) as i32 + from)
    }

    pub fn gen_vec<T>(&mut self, n: usize, range: Range<T>) -> Vec<T>
    where
        T: Number,
    {
        gen_vec(n, |_| self.gen(range.clone()))
    }

    pub fn gen_nonempty_range(&mut self, n: usize) -> Range<usize> {
        let x = self.gen(0..n);
        let y = self.gen(0..n);
        if x <= y {
            x..y + 1
        } else {
            y..x + 1
        }
    }

    pub fn gen_bool(&mut self) -> bool {
        self.gen(0..2) == 0
    }
}
}
}
}
fn main() {
    crate::solution::submit();
}

提出情報

提出日時
問題 E - Pairing Wizards
ユーザ qwerty787788
言語 Rust (1.42.0)
得点 900
コード長 47620 Byte
結果 AC
実行時間 509 ms
メモリ 2548 KiB

ジャッジ結果

セット名 Sample All
得点 / 配点 0 / 0 900 / 900
結果
AC × 3
AC × 65
セット名 テストケース
Sample 00_sample_00.txt, 00_sample_01.txt, 00_sample_02.txt
All 00_sample_00.txt, 00_sample_01.txt, 00_sample_02.txt, 01_max_00.txt, 01_max_01.txt, 02_rnd_00.txt, 02_rnd_01.txt, 02_rnd_02.txt, 02_rnd_03.txt, 02_rnd_04.txt, 02_rnd_05.txt, 02_rnd_06.txt, 02_rnd_07.txt, 02_rnd_08.txt, 02_rnd_09.txt, 03_split_00.txt, 03_split_01.txt, 03_split_02.txt, 03_split_03.txt, 03_split_04.txt, 03_split_05.txt, 03_split_06.txt, 03_split_07.txt, 03_split_08.txt, 03_split_09.txt, 04_split2_00.txt, 04_split2_01.txt, 04_split2_02.txt, 04_split2_03.txt, 04_split2_04.txt, 04_split2_05.txt, 04_split2_06.txt, 04_split2_07.txt, 04_split2_08.txt, 04_split2_09.txt, 05_maximal_01.txt, 05_maximal_02.txt, 05_maximal_03.txt, 05_maximal_04.txt, 05_maximal_05.txt, 05_maximal_06.txt, 05_maximal_07.txt, 05_maximal_08.txt, 05_maximal_09.txt, 05_maximal_10.txt, 05_maximal_11.txt, 05_maximal_12.txt, 05_maximal_13.txt, 05_maximal_14.txt, 05_maximal_15.txt, 05_maximal_16.txt, 05_maximal_17.txt, 05_maximal_18.txt, 05_maximal_19.txt, 05_maximal_20.txt, 05_maximal_21.txt, 05_maximal_22.txt, 05_maximal_23.txt, 05_maximal_24.txt, 05_maximal_25.txt, 05_maximal_26.txt, 05_maximal_27.txt, 05_maximal_28.txt, 05_maximal_29.txt, 05_maximal_30.txt
ケース名 結果 実行時間 メモリ
00_sample_00.txt AC 509 ms 2168 KiB
00_sample_01.txt AC 502 ms 1920 KiB
00_sample_02.txt AC 502 ms 2120 KiB
01_max_00.txt AC 503 ms 2472 KiB
01_max_01.txt AC 502 ms 2284 KiB
02_rnd_00.txt AC 503 ms 2468 KiB
02_rnd_01.txt AC 502 ms 2288 KiB
02_rnd_02.txt AC 502 ms 2316 KiB
02_rnd_03.txt AC 503 ms 2548 KiB
02_rnd_04.txt AC 502 ms 2288 KiB
02_rnd_05.txt AC 503 ms 2324 KiB
02_rnd_06.txt AC 503 ms 2320 KiB
02_rnd_07.txt AC 502 ms 2228 KiB
02_rnd_08.txt AC 503 ms 2072 KiB
02_rnd_09.txt AC 502 ms 2192 KiB
03_split_00.txt AC 503 ms 2220 KiB
03_split_01.txt AC 502 ms 2236 KiB
03_split_02.txt AC 504 ms 2440 KiB
03_split_03.txt AC 503 ms 2268 KiB
03_split_04.txt AC 503 ms 2348 KiB
03_split_05.txt AC 502 ms 2256 KiB
03_split_06.txt AC 503 ms 2504 KiB
03_split_07.txt AC 502 ms 2256 KiB
03_split_08.txt AC 502 ms 2256 KiB
03_split_09.txt AC 502 ms 2292 KiB
04_split2_00.txt AC 502 ms 2152 KiB
04_split2_01.txt AC 502 ms 2252 KiB
04_split2_02.txt AC 502 ms 2200 KiB
04_split2_03.txt AC 502 ms 2340 KiB
04_split2_04.txt AC 502 ms 2332 KiB
04_split2_05.txt AC 502 ms 2272 KiB
04_split2_06.txt AC 502 ms 2084 KiB
04_split2_07.txt AC 502 ms 2292 KiB
04_split2_08.txt AC 503 ms 2240 KiB
04_split2_09.txt AC 502 ms 2300 KiB
05_maximal_01.txt AC 502 ms 2164 KiB
05_maximal_02.txt AC 502 ms 2144 KiB
05_maximal_03.txt AC 502 ms 2172 KiB
05_maximal_04.txt AC 503 ms 2220 KiB
05_maximal_05.txt AC 502 ms 2112 KiB
05_maximal_06.txt AC 502 ms 2132 KiB
05_maximal_07.txt AC 502 ms 2160 KiB
05_maximal_08.txt AC 502 ms 2272 KiB
05_maximal_09.txt AC 502 ms 2300 KiB
05_maximal_10.txt AC 502 ms 2284 KiB
05_maximal_11.txt AC 502 ms 2196 KiB
05_maximal_12.txt AC 502 ms 2240 KiB
05_maximal_13.txt AC 502 ms 2040 KiB
05_maximal_14.txt AC 502 ms 2200 KiB
05_maximal_15.txt AC 502 ms 2308 KiB
05_maximal_16.txt AC 502 ms 2264 KiB
05_maximal_17.txt AC 502 ms 2264 KiB
05_maximal_18.txt AC 502 ms 2224 KiB
05_maximal_19.txt AC 502 ms 2284 KiB
05_maximal_20.txt AC 502 ms 2208 KiB
05_maximal_21.txt AC 502 ms 2160 KiB
05_maximal_22.txt AC 502 ms 2168 KiB
05_maximal_23.txt AC 502 ms 2100 KiB
05_maximal_24.txt AC 502 ms 2204 KiB
05_maximal_25.txt AC 502 ms 2212 KiB
05_maximal_26.txt AC 502 ms 2232 KiB
05_maximal_27.txt AC 502 ms 2220 KiB
05_maximal_28.txt AC 502 ms 2276 KiB
05_maximal_29.txt AC 502 ms 2160 KiB
05_maximal_30.txt AC 502 ms 2116 KiB