QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#853579 | #9727. Barkley III | ucup-team296# | TL | 789ms | 213640kb | Rust | 42.7kb | 2025-01-11 17:39:35 | 2025-01-11 17:39:43 |
Judging History
answer
// https://contest.ucup.ac/contest/1893/problem/9727
use crate::algo_lib::collections::segment_tree::{SegmentTree, SegmentTreeNode};
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::numbers::num_traits::bit_ops::BitOps;
type PreCalc = ();
fn solve(input: &mut Input, out: &mut Output, _test_case: usize, _data: &mut PreCalc) {
let n = input.read_size();
let q = input.read_size();
let a = input.read_long_vec(n);
#[derive(Copy, Clone)]
enum State {
None,
One(usize),
More,
}
#[derive(Clone)]
struct Node {
and: i64,
state: Vec<State>,
delta: i64,
single: State,
}
impl Node {
fn single(a: i64, i: usize) -> Self {
let mut state = Vec::with_capacity(63);
for j in 0..63 {
if a.is_set(j) {
state.push(State::None);
} else {
state.push(State::One(i));
}
}
Node {
and: a,
state,
delta: i64::MAX,
single: State::One(i),
}
}
}
impl SegmentTreeNode for Node {
fn new(_left: usize, _right: usize) -> Self {
Self {
and: i64::MAX,
state: vec![State::None; 63],
delta: i64::MAX,
single: State::More,
}
}
fn join(&mut self, left_val: &Self, right_val: &Self) {
self.and = left_val.and & right_val.and;
for i in 0..63 {
self.state[i] = match (left_val.state[i], right_val.state[i]) {
(State::None, x) | (x, State::None) => x,
_ => State::More,
};
}
}
fn accumulate(&mut self, value: &Self) {
self.and &= value.delta;
for i in 0..63 {
if !value.delta.is_set(i) {
self.state[i] = self.single;
}
}
self.delta &= value.delta;
}
fn reset_delta(&mut self) {
self.delta = i64::MAX;
}
}
let mut st = SegmentTree::gen(n, |i| Node::single(a[i], i));
for _ in 0..q {
let command = input.read_int();
match command {
1 => {
let l = input.read_size() - 1;
let r = input.read_size();
let x = input.read_long();
st.update(
l..r,
&Node {
delta: x,
and: 0,
state: Vec::new(),
single: State::More,
},
);
}
2 => {
let s = input.read_size() - 1;
let x = input.read_long();
st.point_update(s, Node::single(x, s));
}
3 => {
let l = input.read_size() - 1;
let r = input.read_size();
let node = st.query(l..r);
let mut pos = None;
for i in (0..63).rev() {
if let State::One(x) = node.state[i] {
pos = Some(x);
break;
}
}
let ans = if let Some(pos) = pos {
st.query(l..pos).and & st.query(pos + 1..r).and
} else {
node.and
};
out.print_line(ans);
}
_ => unreachable!(),
}
}
}
pub static TEST_TYPE: TestType = TestType::Single;
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,
}
}
fn main() {
let mut sin = std::io::stdin();
let input = crate::algo_lib::io::input::Input::new(&mut sin);
let mut stdout = std::io::stdout();
let output = crate::algo_lib::io::output::Output::new(&mut stdout);
run(input, output);
}
pub mod algo_lib {
pub mod collections {
pub mod bounds {
use std::ops::RangeBounds;
pub fn clamp(range: impl RangeBounds<usize>, n: usize) -> (usize, usize) {
let start = match range.start_bound() {
std::ops::Bound::Included(&x) => x,
std::ops::Bound::Excluded(&x) => x + 1,
std::ops::Bound::Unbounded => 0,
};
let end = match range.end_bound() {
std::ops::Bound::Included(&x) => x + 1,
std::ops::Bound::Excluded(&x) => x,
std::ops::Bound::Unbounded => n,
};
(start, end.min(n))
}
}
pub mod segment_tree {
use crate::algo_lib::collections::bounds::clamp;
use crate::algo_lib::misc::direction::Direction;
use crate::when;
use std::marker::PhantomData;
use std::ops::RangeBounds;
#[allow(unused_variables)]
pub trait SegmentTreeNode {
fn new(left: usize, right: usize) -> Self;
fn join(&mut self, left_val: &Self, right_val: &Self) {}
fn accumulate(&mut self, value: &Self) {}
fn reset_delta(&mut self) {}
}
pub trait Pushable<T>: SegmentTreeNode {
fn push(&mut self, delta: T);
}
impl<T: SegmentTreeNode> Pushable<&T> for T {
fn push(&mut self, delta: &T) {
self.accumulate(delta);
}
}
impl<T: SegmentTreeNode> Pushable<T> for T {
fn push(&mut self, delta: T) {
*self = delta;
}
}
pub trait QueryResult<Result, Args>: SegmentTreeNode {
fn empty_result(args: &Args) -> Result;
fn result(&self, args: &Args) -> Result;
fn join_results(
left_res: Result,
right_res: Result,
args: &Args,
left: usize,
mid: usize,
right: usize,
) -> Result;
}
impl<T: SegmentTreeNode + Clone> QueryResult<T, ()> for T {
fn empty_result(_: &()) -> T {
Self::new(0, 0)
}
fn result(&self, _: &()) -> T {
self.clone()
}
fn join_results(
left_res: T,
right_res: T,
_: &(),
left: usize,
mid: usize,
right: usize,
) -> T {
when! {
left == mid => right_res, right == mid => left_res, else => { let mut res =
Self::new(left, right); res.join(& left_res, & right_res); res },
}
}
}
#[derive(Clone)]
pub struct SegmentTree<Node> {
n: usize,
nodes: Vec<Node>,
}
impl<Node: SegmentTreeNode> SegmentTree<Node> {
pub fn new(n: usize) -> Self {
Self::gen(n, |left| Node::new(left, left + 1))
}
pub fn from_array(arr: Vec<Node>) -> Self {
let n = arr.len();
let mut iter = arr.into_iter();
Self::gen(n, |_| iter.next().unwrap())
}
pub fn gen<F>(n: usize, gen: F) -> Self
where
F: FnMut(usize) -> Node,
{
if n == 0 {
return Self {
n,
nodes: vec![Node::new(0, 0)],
};
}
let mut res = Self {
n,
nodes: Vec::with_capacity(2 * n - 1),
};
res.init(gen);
res
}
fn init<F>(&mut self, mut f: F)
where
F: FnMut(usize) -> Node,
{
self.init_impl(2 * self.n - 2, 0, self.n, &mut f);
}
fn init_impl<F>(&mut self, root: usize, left: usize, right: usize, f: &mut F)
where
F: FnMut(usize) -> Node,
{
if left + 1 == right {
self.nodes.push(f(left));
} else {
let mid = left + ((right - left) >> 1);
let left_child = root - 2 * (right - mid);
let right_child = root - 1;
self.init_impl(left_child, left, mid, f);
self.init_impl(right_child, mid, right, f);
let mut node = Node::new(left, right);
node.join(&self.nodes[left_child], &self.nodes[right_child]);
self.nodes.push(node);
}
}
pub fn point_query(&mut self, at: usize) -> &Node {
assert!(at < self.n);
self.do_point_query(self.nodes.len() - 1, 0, self.n, at)
}
fn do_point_query(
&mut self,
root: usize,
left: usize,
right: usize,
at: usize,
) -> &Node {
if left + 1 == right {
&self.nodes[root]
} else {
let mid = (left + right) >> 1;
self.push_down(root, mid, right);
let left_child = root - 2 * (right - mid);
let right_child = root - 1;
if at < mid {
self.do_point_query(left_child, left, mid, at)
} else {
self.do_point_query(right_child, mid, right, at)
}
}
}
pub fn point_update<T>(&mut self, at: usize, val: T)
where
Node: Pushable<T>,
{
assert!(at < self.n);
self.do_point_update(self.nodes.len() - 1, 0, self.n, at, val);
}
fn do_point_update<T>(
&mut self,
root: usize,
left: usize,
right: usize,
at: usize,
val: T,
)
where
Node: Pushable<T>,
{
if left + 1 == right {
self.nodes[root].push(val);
} else {
let mid = (left + right) >> 1;
self.push_down(root, mid, right);
let left_child = root - 2 * (right - mid);
let right_child = root - 1;
if at < mid {
self.do_point_update(left_child, left, mid, at, val);
} else {
self.do_point_update(right_child, mid, right, at, val);
}
self.join(root, mid, right);
}
}
pub fn point_through_update<'a, T>(&mut self, at: usize, val: &'a T)
where
Node: Pushable<&'a T>,
{
assert!(at < self.n);
self.do_point_through_update(self.nodes.len() - 1, 0, self.n, at, val);
}
fn do_point_through_update<'a, T>(
&mut self,
root: usize,
left: usize,
right: usize,
at: usize,
val: &'a T,
)
where
Node: Pushable<&'a T>,
{
self.nodes[root].push(val);
if left + 1 != right {
let mid = (left + right) >> 1;
self.push_down(root, mid, right);
let left_child = root - 2 * (right - mid);
let right_child = root - 1;
if at < mid {
self.do_point_through_update(left_child, left, mid, at, val);
} else {
self.do_point_through_update(right_child, mid, right, at, val);
}
}
}
pub fn point_operation<Args, Res>(
&mut self,
op: &mut dyn PointOperation<Node, Args, Res>,
args: Args,
) -> Res {
assert_ne!(self.n, 0);
self.do_point_operation(op, self.nodes.len() - 1, 0, self.n, args)
}
fn do_point_operation<Args, Res>(
&mut self,
op: &mut dyn PointOperation<Node, Args, Res>,
root: usize,
left: usize,
right: usize,
args: Args,
) -> Res {
if left + 1 == right {
op.adjust_leaf(&mut self.nodes[root], left, args)
} else {
let mid = (left + right) >> 1;
self.push_down(root, mid, right);
let left_child = root - 2 * (right - mid);
let right_child = root - 1;
let (l, r) = self.nodes.split_at_mut(root);
let (l, m) = l.split_at_mut(right_child);
let direction = op
.select_branch(
&mut r[0],
&mut l[left_child],
&mut m[0],
&args,
left,
mid,
right,
);
let res = match direction {
Direction::Left => {
self.do_point_operation(op, left_child, left, mid, args)
}
Direction::Right => {
self.do_point_operation(op, right_child, mid, right, args)
}
};
self.join(root, mid, right);
res
}
}
pub fn update<'a, T>(&mut self, range: impl RangeBounds<usize>, val: &'a T)
where
Node: Pushable<&'a T>,
{
let (from, to) = clamp(range, self.n);
self.do_update(self.nodes.len() - 1, 0, self.n, from, to, val)
}
pub fn do_update<'a, T>(
&mut self,
root: usize,
left: usize,
right: usize,
from: usize,
to: usize,
val: &'a T,
)
where
Node: Pushable<&'a T>,
{
when! {
left >= to || right <= from => {}, left >= from && right <= to => self
.nodes[root].push(val), else => { let mid = (left + right) >> 1; self
.push_down(root, mid, right); let left_child = root - 2 * (right - mid); let
right_child = root - 1; self.do_update(left_child, left, mid, from, to, val);
self.do_update(right_child, mid, right, from, to, val); self.join(root, mid,
right); },
}
}
pub fn operation<Args, Res>(
&mut self,
range: impl RangeBounds<usize>,
op: &mut dyn Operation<Node, Args, Res>,
args: &Args,
) -> Res {
let (from, to) = clamp(range, self.n);
self.do_operation(self.nodes.len() - 1, 0, self.n, from, to, op, args)
}
pub fn do_operation<Args, Res>(
&mut self,
root: usize,
left: usize,
right: usize,
from: usize,
to: usize,
op: &mut dyn Operation<Node, Args, Res>,
args: &Args,
) -> Res {
when! {
left >= to || right <= from => op.empty_result(left, right, args), left >=
from && right <= to => op.process_result(& mut self.nodes[root], args), else
=> { let mid = (left + right) >> 1; self.push_down(root, mid, right); let
left_child = root - 2 * (right - mid); let right_child = root - 1; let
left_result = self.do_operation(left_child, left, mid, from, to, op, args);
let right_result = self.do_operation(right_child, mid, right, from, to, op,
args); self.join(root, mid, right); op.join_results(left_result,
right_result, args) },
}
}
pub fn binary_search<Res>(
&mut self,
wh: impl FnMut(&Node, &Node) -> Direction,
calc: impl FnMut(&Node, usize) -> Res,
) -> Res {
self.do_binary_search(self.nodes.len() - 1, 0, self.n, wh, calc)
}
fn do_binary_search<Res>(
&mut self,
root: usize,
left: usize,
right: usize,
mut wh: impl FnMut(&Node, &Node) -> Direction,
mut calc: impl FnMut(&Node, usize) -> Res,
) -> Res {
if left + 1 == right {
calc(&self.nodes[root], left)
} else {
let mid = (left + right) >> 1;
self.push_down(root, mid, right);
let left_child = root - 2 * (right - mid);
let right_child = root - 1;
let direction = wh(&self.nodes[left_child], &self.nodes[right_child]);
match direction {
Direction::Left => self.do_binary_search(left_child, left, mid, wh, calc),
Direction::Right => {
self.do_binary_search(right_child, mid, right, wh, calc)
}
}
}
}
fn join(&mut self, root: usize, mid: usize, right: usize) {
let left_child = root - 2 * (right - mid);
let right_child = root - 1;
let (left_node, right_node) = self.nodes.split_at_mut(root);
right_node[0].join(&left_node[left_child], &left_node[right_child]);
}
fn do_push_down(&mut self, parent: usize, to: usize) {
let (left_nodes, right_nodes) = self.nodes.split_at_mut(parent);
left_nodes[to].accumulate(&right_nodes[0]);
}
fn push_down(&mut self, root: usize, mid: usize, right: usize) {
self.do_push_down(root, root - 2 * (right - mid));
self.do_push_down(root, root - 1);
self.nodes[root].reset_delta();
}
pub fn query<T>(&mut self, range: impl RangeBounds<usize>) -> T
where
Node: QueryResult<T, ()>,
{
let (from, to) = clamp(range, self.n);
if from >= to {
Node::empty_result(&())
} else {
self.do_query(self.nodes.len() - 1, 0, self.n, from, to, &())
}
}
pub fn query_with_args<T, Args>(
&mut self,
range: impl RangeBounds<usize>,
args: &Args,
) -> T
where
Node: QueryResult<T, Args>,
{
let (from, to) = clamp(range, self.n);
if from >= to {
Node::empty_result(args)
} else {
self.do_query(self.nodes.len() - 1, 0, self.n, from, to, args)
}
}
fn do_query<T, Args>(
&mut self,
root: usize,
left: usize,
right: usize,
from: usize,
to: usize,
args: &Args,
) -> T
where
Node: QueryResult<T, Args>,
{
if left >= from && right <= to {
self.nodes[root].result(args)
} else {
let mid = (left + right) >> 1;
self.push_down(root, mid, right);
let left_child = root - 2 * (right - mid);
let right_child = root - 1;
when! {
to <= mid => self.do_query(left_child, left, mid, from, to, args), from
>= mid => self.do_query(right_child, mid, right, from, to, args), else =>
{ let left_result = self.do_query(left_child, left, mid, from, to, args);
let right_result = self.do_query(right_child, mid, right, from, to,
args); Node::join_results(left_result, right_result, args, left, mid,
right) },
}
}
}
}
pub trait PointOperation<Node: SegmentTreeNode, Args, Res = Node> {
fn adjust_leaf(&mut self, leaf: &mut Node, at: usize, args: Args) -> Res;
fn select_branch(
&mut self,
root: &mut Node,
left_child: &mut Node,
right_child: &mut Node,
args: &Args,
left: usize,
mid: usize,
right: usize,
) -> Direction;
}
pub struct PointOperationClosure<'s, Node: SegmentTreeNode, Args, Res = Node> {
adjust_leaf: Box<dyn FnMut(&mut Node, usize, Args) -> Res + 's>,
select_branch: Box<
dyn FnMut(
&mut Node,
&mut Node,
&mut Node,
&Args,
usize,
usize,
usize,
) -> Direction + 's,
>,
phantom_node: PhantomData<Node>,
phantom_args: PhantomData<Args>,
phantom_res: PhantomData<Res>,
}
impl<'s, Node: SegmentTreeNode, Args, Res> PointOperationClosure<'s, Node, Args, Res> {
pub fn new<F1, F2>(adjust_leaf: F1, select_branch: F2) -> Self
where
F1: FnMut(&mut Node, usize, Args) -> Res + 's,
F2: FnMut(
&mut Node,
&mut Node,
&mut Node,
&Args,
usize,
usize,
usize,
) -> Direction + 's,
{
Self {
adjust_leaf: Box::new(adjust_leaf),
select_branch: Box::new(select_branch),
phantom_node: Default::default(),
phantom_args: Default::default(),
phantom_res: Default::default(),
}
}
}
impl<'s, Node: SegmentTreeNode, Args, Res> PointOperation<Node, Args, Res>
for PointOperationClosure<'s, Node, Args, Res> {
fn adjust_leaf(&mut self, leaf: &mut Node, at: usize, args: Args) -> Res {
(self.adjust_leaf)(leaf, at, args)
}
fn select_branch(
&mut self,
root: &mut Node,
left_child: &mut Node,
right_child: &mut Node,
args: &Args,
left: usize,
mid: usize,
right: usize,
) -> Direction {
(self.select_branch)(root, left_child, right_child, args, left, mid, right)
}
}
pub trait Operation<Node: SegmentTreeNode, Args, Res = Node> {
fn process_result(&mut self, node: &mut Node, args: &Args) -> Res;
fn join_results(&mut self, left_res: Res, right_res: Res, args: &Args) -> Res;
fn empty_result(&mut self, left: usize, right: usize, args: &Args) -> Res;
}
pub struct OperationClosure<'s, Node: SegmentTreeNode, Args, Res = Node> {
process_result: Box<dyn FnMut(&mut Node, &Args) -> Res + 's>,
join_results: Box<dyn FnMut(Res, Res, &Args) -> Res + 's>,
empty_result: Box<dyn FnMut(usize, usize, &Args) -> Res + 's>,
phantom_node: PhantomData<Node>,
phantom_args: PhantomData<Args>,
phantom_res: PhantomData<Res>,
}
impl<'s, Node: SegmentTreeNode, Args, Res> OperationClosure<'s, Node, Args, Res> {
pub fn new<F1, F2, F3>(
process_result: F1,
join_results: F2,
empty_result: F3,
) -> Self
where
F1: FnMut(&mut Node, &Args) -> Res + 's,
F2: FnMut(Res, Res, &Args) -> Res + 's,
F3: FnMut(usize, usize, &Args) -> Res + 's,
{
Self {
process_result: Box::new(process_result),
join_results: Box::new(join_results),
empty_result: Box::new(empty_result),
phantom_node: Default::default(),
phantom_args: Default::default(),
phantom_res: Default::default(),
}
}
}
impl<'s, Node: SegmentTreeNode, Args, Res> Operation<Node, Args, Res>
for OperationClosure<'s, Node, Args, Res> {
fn process_result(&mut self, node: &mut Node, args: &Args) -> Res {
(self.process_result)(node, args)
}
fn join_results(&mut self, left_res: Res, right_res: Res, args: &Args) -> Res {
(self.join_results)(left_res, right_res, args)
}
fn empty_result(&mut self, left: usize, right: usize, args: &Args) -> Res {
(self.empty_result)(left, right, args)
}
}
}
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;
use std::mem::MaybeUninit;
pub struct Input<'s> {
input: &'s mut (dyn Read + Send),
buf: Vec<u8>,
at: usize,
buf_read: usize,
eol: bool,
}
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,
eol: true,
}
}
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,
eol: true,
}
}
pub fn get(&mut self) -> Option<u8> {
if self.refill_buffer() {
let res = self.buf[self.at];
self.at += 1;
if res == b'\r' {
self.eol = true;
if self.refill_buffer() && self.buf[self.at] == b'\n' {
self.at += 1;
}
return Some(b'\n');
}
self.eol = res == 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) }
}
pub fn is_exhausted(&mut self) -> bool {
self.peek().is_none()
}
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 fn is_eol(&self) -> bool {
self.eol
}
}
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)
}
}
impl<T: Readable, const SIZE: usize> Readable for [T; SIZE] {
fn read(input: &mut Input) -> Self {
unsafe {
let mut res = MaybeUninit::<[T; SIZE]>::uninit();
for i in 0..SIZE {
let ptr: *mut T = (*res.as_mut_ptr()).as_mut_ptr();
ptr.add(i).write(input.read::<T>());
}
res.assume_init()
}
}
}
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
}
}
pub mod output {
use crate::algo_lib::collections::vec_ext::default::default_vec;
use std::cmp::Reverse;
use std::io::{stderr, Stderr, 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,
precision: Option<usize>,
separator: u8,
}
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,
precision: None,
separator: b' ',
}
}
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,
precision: None,
separator: b' ',
}
}
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(self.separator);
}
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;
}
pub fn set_precision(&mut self, precision: usize) {
self.precision = Some(precision);
}
pub fn reset_precision(&mut self) {
self.precision = None;
}
pub fn get_precision(&self) -> Option<usize> {
self.precision
}
pub fn separator(&self) -> u8 {
self.separator
}
pub fn set_separator(&mut self, separator: u8) {
self.separator = separator;
}
}
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(out
.separator); 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 direction {
#[derive(Copy, Clone)]
pub enum Direction {
Left,
Right,
}
}
pub mod test_type {
pub enum TestType {
Single,
MultiNumber,
MultiEof,
}
pub enum TaskType {
Classic,
Interactive,
}
}
pub mod when {
#[macro_export]
macro_rules! when {
{$($cond:expr => $then:expr,)*} => {
match () { $(_ if $cond => $then,)* _ => unreachable!(), }
};
{$($cond:expr => $then:expr,)* else $(=>)? $else:expr $(,)?} => {
match () { $(_ if $cond => $then,)* _ => $else, }
};
}
}
}
pub mod numbers {
pub mod num_traits {
pub mod algebra {
use crate::algo_lib::numbers::num_traits::invertible::Invertible;
use std::ops::{
Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign,
};
pub trait Zero {
fn zero() -> Self;
}
pub trait One {
fn one() -> Self;
}
pub trait AdditionMonoid: Add<Output = Self> + AddAssign + Zero + Eq + Sized {}
impl<T: Add<Output = Self> + AddAssign + Zero + Eq> AdditionMonoid for T {}
pub trait AdditionMonoidWithSub: AdditionMonoid + Sub<Output = Self> + SubAssign {}
impl<T: AdditionMonoid + Sub<Output = Self> + SubAssign> AdditionMonoidWithSub for T {}
pub trait AdditionGroup: AdditionMonoidWithSub + Neg<Output = Self> {}
impl<T: AdditionMonoidWithSub + Neg<Output = Self>> AdditionGroup for T {}
pub trait MultiplicationMonoid: Mul<Output = Self> + MulAssign + One + Eq + Sized {}
impl<T: Mul<Output = Self> + MulAssign + One + Eq> MultiplicationMonoid for T {}
pub trait IntegerMultiplicationMonoid: MultiplicationMonoid + Div<
Output = Self,
> + Rem<Output = Self> + DivAssign + RemAssign {}
impl<
T: MultiplicationMonoid + Div<Output = Self> + Rem<Output = Self> + DivAssign
+ RemAssign,
> IntegerMultiplicationMonoid for T {}
pub trait MultiplicationGroup: MultiplicationMonoid + Div<
Output = Self,
> + DivAssign + Invertible<Output = Self> {}
impl<
T: MultiplicationMonoid + Div<Output = Self> + DivAssign + Invertible<Output = Self>,
> MultiplicationGroup for T {}
pub trait SemiRing: AdditionMonoid + MultiplicationMonoid {}
impl<T: AdditionMonoid + MultiplicationMonoid> SemiRing for T {}
pub trait SemiRingWithSub: AdditionMonoidWithSub + SemiRing {}
impl<T: AdditionMonoidWithSub + SemiRing> SemiRingWithSub for T {}
pub trait Ring: SemiRing + AdditionGroup {}
impl<T: SemiRing + AdditionGroup> Ring for T {}
pub trait IntegerSemiRing: SemiRing + IntegerMultiplicationMonoid {}
impl<T: SemiRing + IntegerMultiplicationMonoid> IntegerSemiRing for T {}
pub trait IntegerSemiRingWithSub: SemiRingWithSub + IntegerSemiRing {}
impl<T: SemiRingWithSub + IntegerSemiRing> IntegerSemiRingWithSub for T {}
pub trait IntegerRing: IntegerSemiRing + Ring {}
impl<T: IntegerSemiRing + Ring> IntegerRing for T {}
pub trait Field: Ring + MultiplicationGroup {}
impl<T: Ring + MultiplicationGroup> Field for T {}
macro_rules! zero_one_integer_impl {
($($t:ident)+) => {
$(impl Zero for $t { fn zero() -> Self { 0 } } impl One for $t { fn one() -> Self
{ 1 } })+
};
}
zero_one_integer_impl!(i128 i64 i32 i16 i8 isize u128 u64 u32 u16 u8 usize);
}
pub mod bit_ops {
use crate::algo_lib::numbers::num_traits::algebra::{One, Zero};
use std::ops::{
BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, RangeInclusive,
Shl, Sub,
};
use std::ops::{ShlAssign, Shr, ShrAssign};
pub trait BitOps: Copy + BitAnd<
Output = Self,
> + BitAndAssign + BitOr<
Output = Self,
> + BitOrAssign + BitXor<
Output = Self,
> + BitXorAssign + Not<
Output = Self,
> + Shl<
usize,
Output = Self,
> + ShlAssign<
usize,
> + Shr<usize, Output = Self> + ShrAssign<usize> + Zero + One + PartialEq {
#[inline]
fn bit(at: usize) -> Self {
Self::one() << at
}
#[inline]
fn is_set(&self, at: usize) -> bool {
(*self >> at & Self::one()) == Self::one()
}
#[inline]
fn set_bit(&mut self, at: usize) {
*self |= Self::bit(at);
}
#[inline]
fn unset_bit(&mut self, at: usize) {
*self &= !Self::bit(at);
}
#[must_use]
#[inline]
fn with_bit(mut self, at: usize) -> Self {
self.set_bit(at);
self
}
#[must_use]
#[inline]
fn without_bit(mut self, at: usize) -> Self {
self.unset_bit(at);
self
}
#[inline]
fn flip_bit(&mut self, at: usize) {
*self ^= Self::bit(at);
}
#[must_use]
#[inline]
fn flipped_bit(mut self, at: usize) -> Self {
self.flip_bit(at);
self
}
fn all_bits(n: usize) -> Self {
let mut res = Self::zero();
for i in 0..n {
res.set_bit(i);
}
res
}
fn iter_all(n: usize) -> RangeInclusive<Self> {
Self::zero()..=Self::all_bits(n)
}
}
pub struct BitIter<T> {
cur: T,
all: T,
ended: bool,
}
impl<T: Copy> BitIter<T> {
pub fn new(all: T) -> Self {
Self {
cur: all,
all,
ended: false,
}
}
}
impl<T: BitOps + Sub<Output = T>> Iterator for BitIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.ended {
return None;
}
let res = self.cur;
if self.cur == T::zero() {
self.ended = true;
} else {
self.cur = (self.cur - T::one()) & self.all;
}
Some(res)
}
}
impl<
T: Copy + BitAnd<Output = Self> + BitAndAssign + BitOr<Output = Self> + BitOrAssign
+ BitXor<Output = Self> + BitXorAssign + Not<Output = Self>
+ Shl<usize, Output = Self> + ShlAssign<usize> + Shr<usize, Output = Self>
+ ShrAssign<usize> + One + Zero + PartialEq,
> BitOps for T {}
pub trait Bits: BitOps {
fn bits() -> u32;
}
macro_rules! bits_integer_impl {
($($t:ident $bits:expr),+) => {
$(impl Bits for $t { fn bits() -> u32 { $bits } })+
};
}
bits_integer_impl!(
i128 128, i64 64, i32 32, i16 16, i8 8, isize 64, u128 128, u64 64, u32 32, u16 16,
u8 8, usize 64
);
}
pub mod invertible {
pub trait Invertible {
type Output;
fn inv(&self) -> Option<Self::Output>;
}
}
}
}
}
详细
Test #1:
score: 100
Accepted
time: 0ms
memory: 2144kb
input:
5 9 7 7 7 6 7 3 1 5 2 1 3 3 1 5 3 1 3 1 1 2 3 3 1 3 2 2 8 3 1 3 3 1 2
output:
7 6 7 3 3 8
result:
ok 6 lines
Test #2:
score: 0
Accepted
time: 0ms
memory: 2108kb
input:
10 10 6760061359215711796 1568091718842717482 1568091718842717482 1568091718842717482 5232472783634052627 8795942500783873690 1568091718842717482 1568091718842717482 1568091718842717482 1568091718842717482 1 3 5 7587422031989082829 3 6 10 1 7 8 5197616143400216932 2 4 2518604563805514908 2 2 4533959...
output:
1568091718842717482 35184908959744 176025477579040 8795942500783873690
result:
ok 4 lines
Test #3:
score: 0
Accepted
time: 1ms
memory: 2332kb
input:
100 100 4263579105072360993 4263579105072360993 4263579105072360993 4263579105072360993 4263579105072360993 4263579105072360993 4263579105072360993 4263579105072360993 4263579105072360993 625967318191814868 4263579105072360993 4263579105072360993 4263579105072360993 4263579105072360993 4263579105072...
output:
576531121047601152 1 576460752303423488 4263579105072360993 1306043896232411137 4263579105072360993 576531121047601152 633397148123136 0 1153488865559840256 1152922054496880128 1730020640668059136 3533641810948498945 67108864 1730020640668059136 0 633397148123136 1729382296723653632 0 17300206406680...
result:
ok 78 lines
Test #4:
score: 0
Accepted
time: 0ms
memory: 4480kb
input:
1000 1000 3368486440884437410 3368486440884437410 3368486440884437410 3368486440884437410 3368486440884437410 3368486440884437410 3368486440884437410 3368486440884437410 3368486440884437410 3368486440884437410 3368486440884437410 3639580211161047627 3368486440884437410 3368486440884437410 3368486440...
output:
3368486440884437410 3368486440884437410 3368486440884437410 2251799981457408 0 0 3368486440884437410 0 3326828075601101216 592509842556584322 0 0 0 0 0 0 37154696925806592 0 0 0 3368486440884437410 0 0 3368486440884437410 0 578998425140330496 0 0 134217728 0 3368486440884437410 2306405959167115264 0...
result:
ok 732 lines
Test #5:
score: 0
Accepted
time: 789ms
memory: 213640kb
input:
100000 100000 4364025563773184234 7745126251050571359 5111681002836044963 7745126251050571359 7745126251050571359 7745126251050571359 7745126251050571359 7745126251050571359 7745126251050571359 7745126251050571359 7745126251050571359 7745126251050571359 7222555899134537718 7745126251050571359 686495...
output:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4613942216556019776 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
result:
ok 75105 lines
Test #6:
score: -100
Time Limit Exceeded
input:
1000000 1000000 5485203341817263234 5485203341817263234 5485203341817263234 5485203341817263234 5485203341817263234 5485203341817263234 5485203341817263234 5485203341817263234 5485203341817263234 5485203341817263234 5485203341817263234 5485203341817263234 5485203341817263234 5485203341817263234 5485...
output:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8796093022208 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 576460754450907136 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0...