/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 540.0 KiB
#2 Accepted 1ms 516.0 KiB
#3 Accepted 12ms 540.0 KiB
#4 Accepted 5ms 284.0 KiB
#5 Accepted 5ms 528.0 KiB
#6 Accepted 7ms 1.125 MiB
#7 Accepted 6ms 3.078 MiB
#8 Accepted 6ms 556.0 KiB
#9 Accepted 7ms 512.0 KiB
#10 Accepted 7ms 520.0 KiB
#11 Accepted 7ms 516.0 KiB
#12 Accepted 5ms 1.215 MiB
#13 Accepted 7ms 1.418 MiB
#14 Accepted 8ms 1.453 MiB
#15 Accepted 10ms 3.156 MiB
#16 Accepted 8ms 3.523 MiB
#17 Accepted 9ms 4.418 MiB
#18 Accepted 9ms 4.332 MiB
#19 Accepted 9ms 5.164 MiB
#20 Accepted 8ms 4.211 MiB
#21 Accepted 9ms 4.164 MiB

Code

// 
pub mod solution {
//{"name":"bb7_e","group":"Manual","url":"","interactive":false,"timeLimit":2000,"tests":[{"input":"","output":""}],"testType":"multiNumber","input":{"type":"stdin","fileName":null,"pattern":null},"output":{"type":"stdout","fileName":null,"pattern":null},"languages":{"java":{"taskClass":"bb7_e"}}}

use crate::algo_lib::collections::iter_ext::collect::IterCollect;
use crate::algo_lib::collections::min_max::MinimMaxim;
use crate::algo_lib::collections::slice_ext::backward::Back;
use crate::algo_lib::io::input::Input;
use crate::algo_lib::io::output::Output;
use crate::algo_lib::misc::test_type::TaskType;

use crate::algo_lib::misc::test_type::TestType;
use crate::algo_lib::string::str::StrReader;

type PreCalc = ();

fn solve(input: &mut Input, out: &mut Output, _test_case: usize, _data: &mut PreCalc) {
    let n = input.read_size();
    let k = input.read_size();
    let s = input.read_str();

    let qs = (0..n).filter(|i| s[*i] == b'?').collect_vec();
    let k = k.min(qs.len());
    let mut na = vec![0];
    let mut nb = vec![0];
    for i in 0..n {
        na.push(na[i] + (s[i] == b'A') as usize);
        nb.push(nb[i] + (s[i] == b'B') as usize);
    }
    let mut cur = 0;
    for i in 0..n {
        if s[i] == b'A' {
            cur += nb[n] - nb[i];
        }
    }
    for &i in qs.iter().rev().take(k) {
        cur += na[i];
    }
    let mut ans = cur;
    for i in 0..k {
        cur += nb[n] - nb[qs[i]];
        cur -= na[qs[Back(k - i - 1)]];
        ans.maxim(cur + (i + 1) * (k - i - 1));
    }
    out.print_line(ans);
}

pub static TEST_TYPE: TestType = TestType::MultiNumber;
pub static TASK_TYPE: TaskType = TaskType::Classic;

pub(crate) fn run(mut input: Input, mut output: Output) -> bool {
    let mut pre_calc = ();

    match TEST_TYPE {
        TestType::Single => solve(&mut input, &mut output, 1, &mut pre_calc),
        TestType::MultiNumber => {
            let t = input.read();
            for i in 1..=t {
                solve(&mut input, &mut output, i, &mut pre_calc);
            }
        }
        TestType::MultiEof => {
            let mut i = 1;
            while input.peek().is_some() {
                solve(&mut input, &mut output, i, &mut pre_calc);
                i += 1;
            }
        }
    }
    output.flush();
    match TASK_TYPE {
        TaskType::Classic => input.is_empty(),
        TaskType::Interactive => true,
    }
}

}
pub mod algo_lib {
pub mod collections {
pub mod iter_ext {
pub mod collect {
pub trait IterCollect<T>: Iterator<Item = T> + Sized {
    fn collect_vec(self) -> Vec<T> {
        self.collect()
    }
}

impl<T, I: Iterator<Item = T> + Sized> IterCollect<T> for I {}
}
}
pub mod min_max {
pub trait MinimMaxim<Rhs = Self>: PartialOrd + Sized {
    fn minim(&mut self, other: Rhs) -> bool;

    fn maxim(&mut self, other: Rhs) -> bool;
}

impl<T: PartialOrd> MinimMaxim for T {
    fn minim(&mut self, other: Self) -> bool {
        if other < *self {
            *self = other;
            true
        } else {
            false
        }
    }

    fn maxim(&mut self, other: Self) -> bool {
        if other > *self {
            *self = other;
            true
        } else {
            false
        }
    }
}

impl<T: PartialOrd> MinimMaxim<T> for Option<T> {
    fn minim(&mut self, other: T) -> bool {
        match self {
            None => {
                *self = Some(other);
                true
            }
            Some(v) => v.minim(other),
        }
    }

    fn maxim(&mut self, other: T) -> bool {
        match self {
            None => {
                *self = Some(other);
                true
            }
            Some(v) => v.maxim(other),
        }
    }
}
}
pub mod slice_ext {
pub mod backward {
use std::ops::Index;
use std::ops::IndexMut;

pub struct Back(pub usize);

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

    fn index(&self, index: Back) -> &Self::Output {
        &self[self.len() - index.0 - 1]
    }
}

impl<T> IndexMut<Back> for [T] {
    fn index_mut(&mut self, index: Back) -> &mut Self::Output {
        &mut self[self.len() - index.0 - 1]
    }
}

impl<T> Index<Back> for Vec<T> {
    type Output = T;

    fn index(&self, index: Back) -> &Self::Output {
        self.as_slice().index(index)
    }
}

impl<T> IndexMut<Back> for Vec<T> {
    fn index_mut(&mut self, index: Back) -> &mut Self::Output {
        self.as_mut_slice().index_mut(index)
    }
}
}
}
pub mod vec_ext {
pub mod default {
pub fn default_vec<T: Default>(len: usize) -> Vec<T> {
    let mut v = Vec::with_capacity(len);
    for _ in 0..len {
        v.push(T::default());
    }
    v
}
}
}
}
pub mod io {
pub mod input {
use crate::algo_lib::collections::vec_ext::default::default_vec;
use std::io::Read;

pub struct Input<'s> {
    input: &'s mut (dyn Read + Send),
    buf: Vec<u8>,
    at: usize,
    buf_read: usize,
}

macro_rules! read_impl {
    ($t: ty, $read_name: ident, $read_vec_name: ident) => {
        pub fn $read_name(&mut self) -> $t {
            self.read()
        }

        pub fn $read_vec_name(&mut self, len: usize) -> Vec<$t> {
            self.read_vec(len)
        }
    };

    ($t: ty, $read_name: ident, $read_vec_name: ident, $read_pair_vec_name: ident) => {
        read_impl!($t, $read_name, $read_vec_name);

        pub fn $read_pair_vec_name(&mut self, len: usize) -> Vec<($t, $t)> {
            self.read_vec(len)
        }
    };
}

impl<'s> Input<'s> {
    const DEFAULT_BUF_SIZE: usize = 4096;

    pub fn new(input: &'s mut (dyn Read + Send)) -> Self {
        Self {
            input,
            buf: default_vec(Self::DEFAULT_BUF_SIZE),
            at: 0,
            buf_read: 0,
        }
    }

    pub fn new_with_size(input: &'s mut (dyn Read + Send), buf_size: usize) -> Self {
        Self {
            input,
            buf: default_vec(buf_size),
            at: 0,
            buf_read: 0,
        }
    }

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

    pub fn peek(&mut self) -> Option<u8> {
        if self.refill_buffer() {
            let res = self.buf[self.at];
            Some(if res == b'\r' { b'\n' } else { res })
        } else {
            None
        }
    }

    pub fn skip_whitespace(&mut self) {
        while let Some(b) = self.peek() {
            if !b.is_ascii_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 c.is_ascii_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()
    }

    //noinspection RsSelfConvention
    pub fn is_empty(&mut self) -> bool {
        self.skip_whitespace();
        self.is_exhausted()
    }

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

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

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

    read_impl!(u32, read_unsigned, read_unsigned_vec);
    read_impl!(u64, read_u64, read_u64_vec);
    read_impl!(usize, read_size, read_size_vec, read_size_pair_vec);
    read_impl!(i32, read_int, read_int_vec, read_int_pair_vec);
    read_impl!(i64, read_long, read_long_vec, read_long_pair_vec);
    read_impl!(i128, read_i128, read_i128_vec);

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

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

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

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

macro_rules! read_integer {
    ($($t:ident)+) => {$(
        impl Readable for $t {
            fn read(input: &mut Input) -> Self {
                input.skip_whitespace();
                let mut c = input.get().unwrap();
                let sgn = match c {
                    b'-' => {
                        c = input.get().unwrap();
                        true
                    }
                    b'+' => {
                        c = input.get().unwrap();
                        false
                    }
                    _ => false,
                };
                let mut res = 0;
                loop {
                    assert!(c.is_ascii_digit());
                    res *= 10;
                    let d = (c - b'0') as $t;
                    if sgn {
                        res -= d;
                    } else {
                        res += d;
                    }
                    match input.get() {
                        None => break,
                        Some(ch) => {
                            if ch.is_ascii_whitespace() {
                                break;
                            } else {
                                c = ch;
                            }
                        }
                    }
                }
                res
            }
        }
    )+};
}

read_integer!(i8 i16 i32 i64 i128 isize u16 u32 u64 u128 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}

impl Read for Input<'_> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.at == self.buf_read {
            self.input.read(buf)
        } else {
            let mut i = 0;
            while i < buf.len() && self.at < self.buf_read {
                buf[i] = self.buf[self.at];
                i += 1;
                self.at += 1;
            }
            Ok(i)
        }
    }
}
}
pub mod output {
use crate::algo_lib::collections::vec_ext::default::default_vec;
use std::cmp::Reverse;
use std::io::stderr;
use std::io::Stderr;
use std::io::Write;

#[derive(Copy, Clone)]
pub enum BoolOutput {
    YesNo,
    YesNoCaps,
    PossibleImpossible,
    Custom(&'static str, &'static str),
}

impl BoolOutput {
    pub fn output(&self, output: &mut Output, val: bool) {
        (if val { self.yes() } else { self.no() }).write(output);
    }

    fn yes(&self) -> &str {
        match self {
            BoolOutput::YesNo => "Yes",
            BoolOutput::YesNoCaps => "YES",
            BoolOutput::PossibleImpossible => "Possible",
            BoolOutput::Custom(yes, _) => yes,
        }
    }

    fn no(&self) -> &str {
        match self {
            BoolOutput::YesNo => "No",
            BoolOutput::YesNoCaps => "NO",
            BoolOutput::PossibleImpossible => "Impossible",
            BoolOutput::Custom(_, no) => no,
        }
    }
}

pub struct Output<'s> {
    output: &'s mut dyn Write,
    buf: Vec<u8>,
    at: usize,
    auto_flush: bool,
    bool_output: BoolOutput,
}

impl<'s> Output<'s> {
    const DEFAULT_BUF_SIZE: usize = 4096;

    pub fn new(output: &'s mut dyn Write) -> Self {
        Self {
            output,
            buf: default_vec(Self::DEFAULT_BUF_SIZE),
            at: 0,
            auto_flush: false,
            bool_output: BoolOutput::YesNoCaps,
        }
    }

    pub fn new_with_auto_flush(output: &'s mut dyn Write) -> Self {
        Self {
            output,
            buf: default_vec(Self::DEFAULT_BUF_SIZE),
            at: 0,
            auto_flush: true,
            bool_output: BoolOutput::YesNoCaps,
        }
    }

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

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

    pub fn print_line<T: Writable>(&mut self, s: T) {
        self.print(s);
        self.put(b'\n');
        self.maybe_flush();
    }

    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]) {
        self.print_per_line_iter(arg.iter());
    }

    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_line_iter<T: Writable, I: Iterator<Item = T>>(&mut self, iter: I) {
        self.print_iter(iter);
        self.put(b'\n');
    }

    pub fn print_per_line_iter<T: Writable, I: Iterator<Item = T>>(&mut self, iter: I) {
        for e in iter {
            e.write(self);
            self.put(b'\n');
        }
    }

    pub fn set_bool_output(&mut self, bool_output: BoolOutput) {
        self.bool_output = bool_output;
    }
}

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;
        }
        self.maybe_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 Writable for u8 {
    fn write(&self, output: &mut Output) {
        output.put(*self);
    }
}

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

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

impl<T: Writable + ?Sized> Writable for &T {
    fn write(&self, output: &mut Output) {
        T::write(self, output)
    }
}

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

impl Writable for () {
    fn write(&self, _output: &mut 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!(u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize);

macro_rules! tuple_writable {
    ($name0:ident $($name:ident: $id:tt )*) => {
        impl<$name0: Writable, $($name: Writable,)*> Writable for ($name0, $($name,)*) {
            fn write(&self, out: &mut Output) {
                self.0.write(out);
                $(
                out.put(b' ');
                self.$id.write(out);
                )*
            }
        }
    }
}

tuple_writable! {T}
tuple_writable! {T U:1}
tuple_writable! {T U:1 V:2}
tuple_writable! {T U:1 V:2 X:3}
tuple_writable! {T U:1 V:2 X:3 Y:4}
tuple_writable! {T U:1 V:2 X:3 Y:4 Z:5}
tuple_writable! {T U:1 V:2 X:3 Y:4 Z:5 A:6}
tuple_writable! {T U:1 V:2 X:3 Y:4 Z:5 A:6 B:7}
tuple_writable! {T U:1 V:2 X:3 Y:4 Z:5 A:6 B:7 C:8}

impl<T: Writable> Writable for Option<T> {
    fn write(&self, output: &mut Output) {
        match self {
            None => (-1).write(output),
            Some(t) => t.write(output),
        }
    }
}

impl Writable for bool {
    fn write(&self, output: &mut Output) {
        let bool_output = output.bool_output;
        bool_output.output(output, *self)
    }
}

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

static mut ERR: Option<Stderr> = None;

pub fn err() -> Output<'static> {
    unsafe {
        if ERR.is_none() {
            ERR = Some(stderr());
        }
        Output::new_with_auto_flush(ERR.as_mut().unwrap())
    }
}
}
}
pub mod misc {
pub mod test_type {
pub enum TestType {
    Single,
    MultiNumber,
    MultiEof,
}

pub enum TaskType {
    Classic,
    Interactive,
}
}
}
pub mod string {
pub mod str {
use crate::algo_lib::collections::iter_ext::collect::IterCollect;
use crate::algo_lib::collections::slice_ext::backward::Back;
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 std::cmp::Ordering;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::hash::Hash;
use std::hash::Hasher;
use std::iter::Copied;
use std::iter::FromIterator;
use std::marker::PhantomData;
use std::ops::Add;
use std::ops::AddAssign;
use std::ops::Deref;
use std::ops::DerefMut;
use std::ops::Index;
use std::ops::IndexMut;
use std::ops::RangeBounds;
use std::slice::Iter;
use std::slice::IterMut;
use std::slice::SliceIndex;
use std::str::FromStr;
use std::vec::IntoIter;

pub enum Str<'s> {
    Extendable(Vec<u8>, PhantomData<&'s [u8]>),
    Owned(Box<[u8]>, PhantomData<&'s [u8]>),
    Ref(&'s [u8]),
}

impl<'s> Str<'s> {
    pub fn substr(&self, range: impl RangeBounds<usize>) -> Str {
        let from = match range.start_bound() {
            std::ops::Bound::Included(&i) => i,
            std::ops::Bound::Excluded(&i) => i + 1,
            std::ops::Bound::Unbounded => 0,
        };
        let to = match range.end_bound() {
            std::ops::Bound::Included(&i) => i + 1,
            std::ops::Bound::Excluded(&i) => i,
            std::ops::Bound::Unbounded => self.len(),
        };
        Str::from(&self[from..to])
    }
}

impl Default for Str<'static> {
    fn default() -> Self {
        Self::new()
    }
}

impl Str<'static> {
    pub fn new() -> Self {
        Str::Extendable(Vec::new(), PhantomData)
    }

    pub fn with_capacity(cap: usize) -> Self {
        Str::Extendable(Vec::with_capacity(cap), PhantomData)
    }
}

impl<'s> Str<'s> {
    pub fn push(&mut self, c: u8) {
        self.transform_to_extendable();
        self.as_extendable().push(c)
    }

    pub fn pop(&mut self) -> Option<u8> {
        self.transform_to_extendable();
        self.as_extendable().pop()
    }

    pub fn as_slice(&self) -> &[u8] {
        match self {
            Str::Extendable(s, _) => s.as_ref(),
            Str::Owned(s, _) => s.as_ref(),
            Str::Ref(s) => s,
        }
    }

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

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn resize(&mut self, new_len: usize, value: u8) {
        self.transform_to_extendable();
        self.as_extendable().resize(new_len, value);
    }

    pub fn iter(&self) -> Copied<Iter<u8>> {
        match self {
            Str::Extendable(v, _) => v.iter(),
            Str::Owned(v, _) => v.iter(),
            Str::Ref(v) => v.iter(),
        }
        .copied()
    }

    pub fn iter_mut(&mut self) -> IterMut<u8> {
        self.transform_to_owned();
        self.as_mut_slice().iter_mut()
    }

    pub fn sort(&mut self) {
        self.transform_to_owned();
        self.as_mut_slice().sort_unstable();
    }

    pub fn into_owned(mut self) -> Str<'static> {
        self.transform_to_owned();
        match self {
            Str::Extendable(v, _) => Str::Extendable(v, PhantomData),
            Str::Owned(v, _) => Str::Owned(v, PhantomData),
            _ => unreachable!(),
        }
    }

    fn transform_to_extendable(&mut self) {
        match self {
            Str::Extendable(_, _) => {}
            Str::Owned(_, _) => {
                let mut fake = Str::new();
                std::mem::swap(self, &mut fake);
                if let Str::Owned(s, _) = fake {
                    *self = Str::Extendable(s.into_vec(), PhantomData)
                } else {
                    unreachable!();
                }
            }
            Str::Ref(s) => *self = Str::Extendable(s.to_vec(), PhantomData),
        }
    }

    fn as_extendable(&mut self) -> &mut Vec<u8> {
        match self {
            Str::Extendable(s, _) => s,
            _ => panic!("unreachable"),
        }
    }

    fn transform_to_owned(&mut self) {
        if let Str::Ref(s) = self {
            *self = Str::Owned(s.to_vec().into_boxed_slice(), PhantomData)
        }
    }

    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        self.transform_to_owned();
        match self {
            Str::Extendable(s, _) => s.as_mut_slice(),
            Str::Owned(s, _) => s.as_mut(),
            _ => panic!("unreachable"),
        }
    }

    pub fn into_string(self) -> String {
        match self {
            Str::Extendable(v, _) => unsafe { String::from_utf8_unchecked(v) },
            Str::Owned(v, _) => unsafe { String::from_utf8_unchecked(v.into_vec()) },
            Str::Ref(v) => String::from_utf8_lossy(v).into_owned(),
        }
    }

    pub fn reverse(&mut self) {
        self.as_mut_slice().reverse();
    }

    pub fn trim(&self) -> Str<'_> {
        let mut start = 0;
        let mut end = self.len();
        while start < end && (self[start] as char).is_whitespace() {
            start += 1;
        }
        while start < end && (self[end - 1] as char).is_whitespace() {
            end -= 1;
        }
        self[start..end].into()
    }

    pub fn split<'a, 'b>(&'a self, sep: impl Into<Str<'b>>) -> Vec<Str<'a>>
    where
        's: 'a,
    {
        let sep = sep.into();
        let mut res = Vec::new();
        let mut start = 0;
        for i in 0..self.len() {
            if self[i..].starts_with(sep.as_slice()) {
                res.push(self[start..i].into());
                start = i + sep.len();
            }
        }
        res.push(self[start..].into());
        res
    }

    pub fn parse<F: FromStr>(self) -> F
    where
        F::Err: Debug,
    {
        self.into_string().parse().unwrap()
    }

    pub fn parse_vec<T: Readable>(&self) -> Vec<T> {
        let mut bytes = self.as_slice();
        let mut input = Input::new(&mut bytes);
        let mut res = Vec::new();
        while !input.is_exhausted() {
            res.push(input.read());
        }
        res
    }

    pub fn qty(&self, from: u8, to: u8) -> Vec<usize> {
        let mut res = vec![0; (to - from + 1) as usize];
        for &c in self.as_slice() {
            res[(c - from) as usize] += 1;
        }
        res
    }

    pub fn qty_lower(&self) -> Vec<usize> {
        self.qty(b'a', b'z')
    }
}

impl<'s> IntoIterator for Str<'s> {
    type Item = u8;
    type IntoIter = IntoIter<u8>;

    #[allow(clippy::unnecessary_to_owned)]
    fn into_iter(self) -> Self::IntoIter {
        match self {
            Str::Extendable(v, _) => v.into_iter(),
            Str::Owned(v, _) => v.into_vec().into_iter(),
            Str::Ref(v) => v.to_vec().into_iter(),
        }
    }
}

impl From<String> for Str<'static> {
    fn from(s: String) -> Self {
        Str::Extendable(s.into(), PhantomData)
    }
}

impl<'s> From<&'s str> for Str<'s> {
    fn from(s: &'s str) -> Self {
        Str::Ref(s.as_bytes())
    }
}

impl From<Vec<u8>> for Str<'static> {
    fn from(s: Vec<u8>) -> Self {
        Str::Extendable(s, PhantomData)
    }
}

impl<'s> From<&'s [u8]> for Str<'s> {
    fn from(s: &'s [u8]) -> Self {
        Str::Ref(s)
    }
}

impl<'s, const N: usize> From<&'s [u8; N]> for Str<'s> {
    fn from(s: &'s [u8; N]) -> Self {
        Str::Ref(s)
    }
}

impl<'s> From<&'s String> for Str<'s> {
    fn from(s: &'s String) -> Self {
        Str::Ref(s.as_bytes())
    }
}

impl<'s> From<&'s Vec<u8>> for Str<'s> {
    fn from(s: &'s Vec<u8>) -> Self {
        Str::Ref(s.as_slice())
    }
}

impl From<u8> for Str<'static> {
    fn from(c: u8) -> Self {
        Str::Owned(Box::new([c]), PhantomData)
    }
}

impl From<char> for Str<'static> {
    fn from(c: char) -> Self {
        Str::from(c as u8)
    }
}

impl<'s, 't: 's> From<&'s Str<'t>> for Str<'s> {
    fn from(value: &'s Str<'t>) -> Self {
        Str::Ref(value.as_slice())
    }
}

impl<R: SliceIndex<[u8]>> Index<R> for Str<'_> {
    type Output = R::Output;

    fn index(&self, index: R) -> &Self::Output {
        self.as_slice().index(index)
    }
}

impl<R: SliceIndex<[u8]>> IndexMut<R> for Str<'_> {
    fn index_mut(&mut self, index: R) -> &mut Self::Output {
        self.transform_to_owned();
        self.as_mut_slice().index_mut(index)
    }
}

impl Clone for Str<'_> {
    fn clone(&self) -> Self {
        match self {
            Str::Extendable(s, _) => s.clone().into(),
            Str::Owned(s, _) => s.to_vec().into(),
            Str::Ref(s) => Str::Ref(s),
        }
    }
}

impl<'r, 's, S: Into<Str<'r>>> AddAssign<S> for Str<'s> {
    fn add_assign(&mut self, rhs: S) {
        self.transform_to_extendable();
        self.as_extendable()
            .extend_from_slice(rhs.into().as_slice());
    }
}

impl<'r, 's, S: Into<Str<'r>>> Add<S> for Str<'s> {
    type Output = Str<'s>;

    fn add(mut self, rhs: S) -> Self::Output {
        self += rhs;
        self
    }
}

impl Readable for Str<'static> {
    fn read(input: &mut Input) -> Self {
        input.next_token().unwrap().into()
    }
}

impl Writable for Str<'_> {
    fn write(&self, output: &mut Output) {
        for c in self.as_slice() {
            output.put(*c);
        }
        output.maybe_flush();
    }
}

impl Display for Str<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        <String as Display>::fmt(&String::from_utf8(self.as_slice().to_vec()).unwrap(), f)
    }
}

impl Hash for Str<'_> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_slice().hash(state);
    }
}

impl<'r> PartialEq<Str<'r>> for Str<'_> {
    fn eq(&self, other: &Str<'r>) -> bool {
        self.as_slice().eq(other.as_slice())
    }
}

impl Eq for Str<'_> {}

impl<'r> PartialOrd<Str<'r>> for Str<'_> {
    fn partial_cmp(&self, other: &Str<'r>) -> Option<Ordering> {
        self.as_slice().partial_cmp(other.as_slice())
    }
}

impl Ord for Str<'_> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_slice().cmp(other.as_slice())
    }
}

impl FromIterator<u8> for Str<'static> {
    fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
        Self::Extendable(iter.into_iter().collect_vec(), Default::default())
    }
}

impl<'r> FromIterator<&'r u8> for Str<'static> {
    fn from_iter<T: IntoIterator<Item = &'r u8>>(iter: T) -> Self {
        Self::Extendable(iter.into_iter().cloned().collect_vec(), Default::default())
    }
}

impl Deref for Str<'_> {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl DerefMut for Str<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_slice()
    }
}

pub trait StrReader {
    fn read_str(&mut self) -> Str<'static>;
    fn read_str_vec(&mut self, n: usize) -> Vec<Str<'static>>;
    fn read_line(&mut self) -> Str<'static>;
    fn read_line_vec(&mut self, n: usize) -> Vec<Str<'static>>;
    fn read_lines(&mut self) -> Vec<Str<'static>>;
}

impl StrReader for Input<'_> {
    fn read_str(&mut self) -> Str<'static> {
        self.read()
    }

    fn read_str_vec(&mut self, n: usize) -> Vec<Str<'static>> {
        self.read_vec(n)
    }

    fn read_line(&mut self) -> Str<'static> {
        let mut res = Str::new();
        while let Some(c) = self.get() {
            if c == b'\n' {
                break;
            }
            res.push(c);
        }
        res
    }

    fn read_line_vec(&mut self, n: usize) -> Vec<Str<'static>> {
        let mut res = Vec::with_capacity(n);
        for _ in 0..n {
            res.push(self.read_line());
        }
        res
    }

    fn read_lines(&mut self) -> Vec<Str<'static>> {
        let mut res = Vec::new();
        while !self.is_exhausted() {
            res.push(self.read_line());
        }
        if let Some(s) = res.last() {
            if s.is_empty() {
                res.pop();
            }
        }
        res
    }
}

impl Index<Back> for Str<'_> {
    type Output = u8;

    fn index(&self, index: Back) -> &Self::Output {
        &self[self.len() - index.0 - 1]
    }
}

impl IndexMut<Back> for Str<'_> {
    fn index_mut(&mut self, index: Back) -> &mut Self::Output {
        let len = self.len();
        &mut self[len - index.0 - 1]
    }
}

impl AsRef<[u8]> for Str<'_> {
    fn as_ref(&self) -> &[u8] {
        self.as_slice()
    }
}
}
}
}
fn main() {
    let mut sin = std::io::stdin();
    let input = algo_lib::io::input::Input::new(&mut sin);
    let mut stdout = std::io::stdout();
    let output = algo_lib::io::output::Output::new(&mut stdout);
    solution::run(input, output);
}

Information

Submit By
Type
Submission
Problem
P1110 Subsequence of AB
Contest
Brain Booster #7
Language
Rust 2021 (Rust 1.75.0)
Submit At
2024-11-05 15:01:55
Judged At
2024-11-05 15:01:55
Judged By
Score
100
Total Time
12ms
Peak Memory
5.164 MiB