use std::cmp;
use std::fs::File;
use std::io::prelude::*;
use std::io::{self, BufRead, BufWriter};
use std::path::Path;
enum Command {
Insert(i32),
Delete(i32),
Lookup(i32),
QueryMaxDiff,
QueryMinDiff,
}
trait Solution {
fn execute(&mut self, cmd: Command) -> Option<i32>;
}
const RANGE: i32 = 1_000_000_000;
#[derive(Clone)]
struct NodeAgg {
min: i32,
max: i32,
min_diff: i32,
}
impl NodeAgg {
fn default() -> Self {
Self {
max: 0,
min: RANGE,
min_diff: RANGE,
}
}
#[inline]
fn is_set(&self) -> bool {
self.max != 0
}
}
struct Node {
left: Option<Box<Node>>,
right: Option<Box<Node>>,
agg: NodeAgg,
}
impl Node {
fn new() -> Self {
Self {
left: None,
right: None,
agg: NodeAgg {
min: RANGE,
min_diff: RANGE,
max: 0,
},
}
}
#[inline]
fn mid(lo: i32, hi: i32) -> i32 {
lo + (hi - lo) / 2
}
#[inline]
fn is_leaf(lo: i32, hi: i32) -> bool {
lo == hi
}
fn update(&mut self, x: i32, set: bool, lo: i32, hi: i32) -> bool {
if Self::is_leaf(lo, hi) {
if self.agg.is_set() == set {
return false;
}
self.agg = match set {
true => NodeAgg {
max: x,
min: x,
min_diff: RANGE,
},
false => NodeAgg::default(),
};
return true;
}
let mid = Self::mid(lo, hi);
let left_range = (0..=mid).contains(&x);
let did_update = match (left_range, self.left.as_mut(), self.right.as_mut()) {
(true, Some(child), _) => child.update(x, set, lo, mid),
(false, _, Some(child)) => child.update(x, set, mid + 1, hi),
(true, None, _) => {
self.left = Some(Box::new(Node::new()));
self.left.as_mut().unwrap().update(x, set, lo, mid)
}
(false, _, None) => {
self.right = Some(Box::new(Node::new()));
self.right.as_mut().unwrap().update(x, set, mid + 1, hi)
}
};
if did_update {
self.update_agg();
}
did_update
}
fn update_agg(&mut self) {
self.agg = match (self.left.as_ref(), self.right.as_ref()) {
(Some(left), Some(right)) => NodeAgg {
max: cmp::max(left.agg.max, right.agg.max),
min: cmp::min(left.agg.min, right.agg.min),
min_diff: self.compute_min_diff(&left.agg, &right.agg),
},
(Some(child), None) | (None, Some(child)) => child.agg.clone(),
(None, None) => NodeAgg::default(),
};
if !self.agg.is_set() {
self.left = None;
self.right = None;
}
}
#[inline]
fn compute_min_diff(&self, l: &NodeAgg, r: &NodeAgg) -> i32 {
let mut res = cmp::min(l.min_diff, r.min_diff);
if l.is_set() && r.is_set() {
res = cmp::min(res, r.min - l.max)
}
res
}
fn has(&self, x: i32, lo: i32, hi: i32) -> bool {
if !self.agg.is_set() {
false
} else if Self::is_leaf(lo, hi) {
true
} else {
let mid = Self::mid(lo, hi);
match (
(0..=mid).contains(&x),
self.left.as_ref(),
self.right.as_ref(),
) {
(true, Some(child), _) => child.has(x, lo, mid),
(false, _, Some(child)) => child.has(x, mid + 1, hi),
_ => false,
}
}
}
#[inline]
fn opt_bound(bound: i32) -> Option<i32> {
match bound {
0 | RANGE => None,
x => Some(x),
}
}
fn max(&self) -> Option<i32> {
Self::opt_bound(self.agg.max)
}
fn min(&self) -> Option<i32> {
Self::opt_bound(self.agg.min)
}
fn min_diff(&self) -> Option<i32> {
Self::opt_bound(self.agg.min_diff)
}
}
struct IntervalTreeSolution {
root: Node,
}
impl IntervalTreeSolution {
fn new() -> Self {
Self { root: Node::new() }
}
}
impl Solution for IntervalTreeSolution {
fn execute(&mut self, cmd: Command) -> Option<i32> {
use Command::*;
match cmd {
Insert(x) => {
self.root.update(x, true, 1, RANGE);
None
}
Delete(x) => match self.root.update(x, false, 1, RANGE) {
true => None,
false => Some(-1),
},
Lookup(x) => match self.root.has(x, 1, RANGE) {
true => Some(1),
false => Some(0),
},
QueryMaxDiff => match (self.root.min(), self.root.max()) {
(Some(a), Some(b)) if a != b => Some(b - a),
_ => Some(-1),
},
QueryMinDiff => Some(self.root.min_diff().unwrap_or(-1)),
}
}
}
fn run<S: Solution>(s: &mut S, in_: &mut Input, out: &mut Output) {
for x in in_ {
if let Some(y) = s.execute(x) {
out.put(y);
}
}
out.done();
}
fn main() {
let mut input = Input::from_path("zeap.in");
let mut output = Output::from_path("zeap.out");
// let mut sol = BTreeSolution::new();
let mut sol = IntervalTreeSolution::new();
run(&mut sol, &mut input, &mut output);
}
struct Output {
out: io::BufWriter<File>,
}
impl Output {
fn from_path<P>(filename: P) -> Self
where
P: AsRef<Path>,
{
let file = File::create(filename).expect("failed to open output");
Self {
out: BufWriter::new(file),
}
}
fn put(&mut self, x: i32) {
write!(self.out, "{}\n", x).unwrap();
}
fn done(&mut self) {
self.out.flush().expect("failed to close output")
}
}
struct Input {
lines: io::Lines<io::BufReader<File>>,
}
impl Input {
fn from_path<P>(filename: P) -> Self
where
P: AsRef<Path>,
{
let file = File::open(filename).expect("failed to open input");
Self {
lines: io::BufReader::new(file).lines(),
}
}
}
impl Iterator for Input {
type Item = Command;
fn next(&mut self) -> Option<Command> {
let line = self.lines.next()?.ok()?;
let args: Vec<_> = line.split(" ").collect();
let op = args[0];
let op_arg = args.get(1).map(|x_str| x_str.parse::<i32>().ok());
match (op, op_arg) {
("I", Some(Some(x))) => Some(Command::Insert(x)),
("S", Some(Some(x))) => Some(Command::Delete(x)),
("C", Some(Some(x))) => Some(Command::Lookup(x)),
("MAX", None) => Some(Command::QueryMaxDiff),
("MIN", None) => Some(Command::QueryMinDiff),
_ => panic!("couldn't parse input {:?}", line),
}
}
}