QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#289785 | #7862. Land Trade | ucup-team296# | AC ✓ | 218ms | 11932kb | Rust | 56.0kb | 2023-12-24 00:25:05 | 2023-12-24 00:25:06 |
Judging History
answer
pub mod solution {
//{"name":"f","group":"Manual","url":"","interactive":false,"timeLimit":2000,"tests":[{"input":"","output":""},{"input":"","output":""},{"input":"","output":""}],"testType":"single","input":{"type":"stdin","fileName":null,"pattern":null},"output":{"type":"stdout","fileName":null,"pattern":null},"languages":{"java":{"taskClass":"f"}}}
use crate::f;
use crate::algo_lib::geometry::line::Line;
use crate::algo_lib::geometry::point::PointT;
use crate::algo_lib::geometry::polygon::PolygonT;
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::ord_f64::OrdF64;
#[allow(unused)]
use crate::dbg;
use crate::out;
use crate::out_line;
#[derive(Debug)]
enum Formula {
Atomic(Line),
And(Box<Formula>, Box<Formula>),
Or(Box<Formula>, Box<Formula>),
Xor(Box<Formula>, Box<Formula>),
Not(Box<Formula>),
}
fn parse_line(s: &[u8]) -> (Line, &[u8]) {
let mut to = 0usize;
let mut numbers: Vec<i64> = vec![];
let mut cur_number = vec![];
loop {
if s[to] == b',' || s[to] == b']' {
let ss = String::from_utf8(cur_number).unwrap();
let value: i64 = ss.parse().unwrap();
numbers.push(value);
cur_number = vec![];
} else {
cur_number.push(s[to]);
}
if s[to] == b']' {
break;
}
to += 1;
}
assert_eq!(numbers.len(), 3);
let line = Line::new3(numbers[0], numbers[1], numbers[2]);
(line, &s[to + 1..])
}
fn parse(s: &[u8]) -> (Box<Formula>, &[u8]) {
assert!(!s.is_empty());
let c = s[0];
if c == b'(' {
let next_c = s[1];
if next_c == b'!' {
let (formula, rest) = parse(&s[2..]);
assert!(rest[0] == b')');
(Box::new(Formula::Not(formula)), &rest[1..])
} else {
let (left, rest) = parse(&s[1..]);
let c = rest[0];
let (right, rest) = parse(&rest[1..]);
assert!(rest[0] == b')');
let rest = &rest[1..];
if c == b'&' {
(Box::new(Formula::And(left, right)), rest)
} else if c == b'|' {
return (Box::new(Formula::Or(left, right)), rest);
} else if c == b'^' {
return (Box::new(Formula::Xor(left, right)), rest);
} else {
panic!("Unknown operation {}", c as char);
}
}
} else {
assert!(c == b'[');
let (line, rest) = parse_line(&s[1..]);
(Box::new(Formula::Atomic(line)), rest)
}
}
fn calc_all_lines(f: &Formula, all_lines: &mut Vec<Line>) {
match f {
Formula::Atomic(line) => {
all_lines.push(line.clone());
}
Formula::And(left, right) => {
calc_all_lines(left, all_lines);
calc_all_lines(right, all_lines);
}
Formula::Or(left, right) => {
calc_all_lines(left, all_lines);
calc_all_lines(right, all_lines);
}
Formula::Xor(left, right) => {
calc_all_lines(left, all_lines);
calc_all_lines(right, all_lines);
}
Formula::Not(formula) => {
calc_all_lines(formula, all_lines);
}
}
}
type Point = PointT<OrdF64>;
fn calc_formula(f: &Formula, p: Point) -> i32 {
match f {
Formula::Atomic(line) => {
let res = line.a * p.x + line.b * p.y + line.c;
if res >= f!(0.0) {
1
} else {
0
}
}
Formula::And(left, right) => calc_formula(left, p) & calc_formula(right, p),
Formula::Or(left, right) => calc_formula(left, p) | calc_formula(right, p),
Formula::Xor(left, right) => calc_formula(left, p) ^ calc_formula(right, p),
Formula::Not(formula) => 1 - calc_formula(formula, p),
}
}
fn solve(input: &mut Input, _test_case: usize) {
let xmin = input.i64();
let xmax = input.i64();
let ymin = input.i64();
let ymax = input.i64();
let s = input.string();
let (formula, rest) = parse(&s);
assert!(rest.is_empty());
// dbg!(formula);
let mut all_lines = vec![];
calc_all_lines(&formula, &mut all_lines);
{
let a = (xmin, ymin);
let b = (xmin, ymax);
let c = (xmax, ymax);
let d = (xmax, ymin);
all_lines.push(Line::new_gcd(a, b));
all_lines.push(Line::new_gcd(b, c));
all_lines.push(Line::new_gcd(c, d));
all_lines.push(Line::new_gcd(d, a));
}
for line in all_lines.iter_mut() {
line.norm();
}
all_lines.sort();
all_lines.dedup();
let mut all_points = vec![];
let mut on_line = vec![vec![]; all_lines.len()];
for i in 0..all_lines.len() {
for j in i + 1..all_lines.len() {
if let Some(p) = all_lines[i].intersect(&all_lines[j]) {
all_points.push(p);
}
}
}
const EPS: f64 = 1e-9;
let cmp = |p1: &Point, p2: &Point| {
let dx = (p1.x - p2.x).abs().0;
if dx < EPS {
p1.y.partial_cmp(&p2.y).unwrap()
} else {
p1.x.partial_cmp(&p2.x).unwrap()
}
};
all_points.sort_by(cmp);
all_points.dedup_by(|p1, p2| {
let dx = (p1.x - p2.x).abs().0;
let dy = (p1.y - p2.y).abs().0;
dx < EPS && dy < EPS
});
for i in 0..all_lines.len() {
for j in 0..all_points.len() {
if all_lines[i].on_line(&all_points[j]) {
on_line[i].push(j);
}
}
on_line[i].sort();
}
let mut all_edges = vec![];
let mut g = vec![vec![]; all_points.len()];
for i in 0..all_lines.len() {
for w in on_line[i].windows(2) {
let from = w[0];
let to = w[1];
all_edges.push((from, to));
g[from].push(all_edges.len() - 1);
all_edges.push((to, from));
g[to].push(all_edges.len() - 1);
}
}
for v in 0..g.len() {
g[v].sort_by(|&to1, &to2| {
let p1 = all_points[all_edges[to1].1] - all_points[v];
let p2 = all_points[all_edges[to2].1] - all_points[v];
let s1 = p1.side();
let s2 = p2.side();
if s1 != s2 {
s1.cmp(&s2)
} else {
Point::vect_mul2(&p1, &p2).cmp(&f!(0.0))
}
});
}
let mut edge_pos = vec![usize::MAX; all_edges.len()];
for v in 0..g.len() {
for i in 0..g[v].len() {
let to = g[v][i];
edge_pos[to] = i;
}
}
let mut seen = vec![false; all_edges.len()];
let mut res = 0.0;
for start_edge in 0..all_edges.len() {
if seen[start_edge] {
continue;
}
let mut cur_edge = start_edge;
let mut points = vec![];
while !seen[cur_edge] {
seen[cur_edge] = true;
let (fr, to) = all_edges[cur_edge];
points.push(all_points[fr]);
let pos = edge_pos[cur_edge ^ 1];
let need_pos = (pos + 1) % g[to].len();
cur_edge = g[to][need_pos];
}
let polygon = PolygonT::new(points);
let area = polygon.area_signed().0;
// dbg!(area, polygon);
if area < 0.0 {
// SKIP
continue;
}
let center = polygon.center_of_gravity();
if center.x >= xmin.into()
&& center.x <= xmax.into()
&& center.y >= ymin.into()
&& center.y <= ymax.into()
{
let formula_res = calc_formula(&formula, center);
// dbg!("GOOD!", formula_res);
if formula_res == 1 {
res += area.abs();
}
}
}
out_line!(res);
}
pub(crate) fn run(mut input: Input) -> bool {
solve(&mut input, 1);
output().flush();
true
}
#[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
}
#[allow(clippy::len_without_is_empty)]
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_all(&[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 * ½
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 geometry {
pub mod direction {
use crate::algo_lib::geometry::point::PointT;
use crate::algo_lib::misc::num_traits::Number;
use std::cmp::Ordering;
///
/// Sorted counter-clock-wise
/// starting from (0;0) -> (inf; 0)
///
pub struct DirectionT<T>(PointT<T>)
where
T: Number;
#[derive(Ord, PartialOrd, Eq, PartialEq)]
enum Side {
PositiveY,
NegativeY,
}
impl<T> DirectionT<T>
where
T: Number,
{
pub fn new(from: PointT<T>, to: PointT<T>) -> Self {
Self(to - from)
}
pub fn inverse(&self) -> Self {
Self(PointT::ZERO - self.0)
}
fn side(&self) -> Side {
if self.0.y > T::ZERO || (self.0.y == T::ZERO && self.0.x >= T::ZERO) {
Side::PositiveY
} else {
Side::NegativeY
}
}
}
impl<T> PartialEq<Self> for DirectionT<T>
where
T: Number + Ord,
{
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl<T> Eq for DirectionT<T> where T: Number + Ord {}
impl<T> PartialOrd<Self> for DirectionT<T>
where
T: Number + Ord,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(
self.side().cmp(&other.side()).then(
PointT::<T>::vect_mul2(&self.0, &other.0)
.cmp(&T::ZERO)
.reverse(),
),
)
}
}
impl<T> Ord for DirectionT<T>
where
T: Number + Ord,
{
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
}
pub mod line {
use crate::algo_lib::geometry::point::PointT;
use crate::algo_lib::math::gcd::gcd;
use crate::algo_lib::misc::num_traits::HasConstants;
use crate::algo_lib::misc::ord_f64::OrdF64;
use std::fmt::Debug;
type Point = PointT<OrdF64>;
// a*x + b*y + c = 0
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Line {
pub a: OrdF64,
pub b: OrdF64,
pub c: OrdF64,
}
impl Line {
pub fn new(p1: &Point, p2: &Point) -> Self {
let a = p2.y - p1.y;
let b = p1.x - p2.x;
let res = Self {
a,
b,
c: -(p1.x * a + p1.y * b),
};
debug_assert!(res.on_line(p1));
debug_assert!(res.on_line(p2));
res
}
pub fn new_gcd(p1: (i64, i64), p2: (i64, i64)) -> Self {
let mut a = p2.1 - p1.1;
let mut b = p1.0 - p2.0;
let mut c = -(p1.0 * a + p1.1 * b);
let mut g = gcd(a, b);
g = gcd(g, c);
g = g.abs();
a /= g;
b /= g;
c /= g;
Self {
a: a.into(),
b: b.into(),
c: c.into(),
}
}
pub fn norm(&mut self) {
if self.a > OrdF64::EPS {
} else if self.a < -OrdF64::EPS {
self.a = -self.a;
self.b = -self.b;
self.c = -self.c;
} else if self.b > OrdF64::EPS {
return;
} else if self.b < -OrdF64::EPS {
self.b = -self.b;
self.c = -self.c;
}
}
pub fn new3(mut a: i64, mut b: i64, mut c: i64) -> Self {
let mut g = gcd(a, b);
g = gcd(g, c);
g = g.abs();
a /= g;
b /= g;
c /= g;
let res = Self {
a: a.into(),
b: b.into(),
c: c.into(),
};
debug_assert!(res.a != OrdF64::ZERO || res.b != OrdF64::ZERO);
res
}
pub fn on_line(&self, p: &Point) -> bool {
(self.a * p.x + self.b * p.y + self.c).eq_with_default_eps(&OrdF64::ZERO)
}
pub fn intersect(&self, other: &Self) -> Option<Point> {
let denom = self.b * other.a - other.b * self.a;
if denom.eq_with_default_eps(&OrdF64::ZERO) {
return None;
}
let y_num = other.c * self.a - self.c * other.a;
let x_num = self.c * other.b - other.c * self.b;
let res = Point::new(x_num / denom, y_num / denom);
debug_assert!(
self.abs_dist(&res)
.eq_with_eps(&OrdF64::ZERO, OrdF64::SMALL_EPS),
"line = {:?}, p = {:?}, dist = {:?}",
self,
res,
self.abs_dist(&res)
);
debug_assert!(
other
.abs_dist(&res)
.eq_with_eps(&OrdF64::ZERO, OrdF64::SMALL_EPS),
"line = {:?}, p = {:?}, dist = {:?}",
other,
res,
self.abs_dist(&res)
);
Some(res)
}
pub fn signed_dist(&self, p: &Point) -> OrdF64 {
(self.a * p.x + self.b * p.y + self.c) / (self.a * self.a + self.b * self.b).sqrt()
}
pub fn abs_dist(&self, p: &Point) -> OrdF64 {
self.signed_dist(p).abs()
}
pub fn abs_dist2(&self, p: &Point) -> OrdF64 {
let z = self.a * p.x + self.b * p.y + self.c;
z * z / (self.a * self.a + self.b * self.b)
}
pub fn closest_to_zero(&self) -> Point {
let den = self.a * self.a + self.b * self.b;
Point::new(-self.a * self.c / den, -self.b * self.c / den)
}
}
}
pub mod point {
use crate::algo_lib::collections::array_2d::Array2D;
use crate::f;
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::iters::shifts::Shift;
use crate::algo_lib::misc::num_traits::Number;
use crate::algo_lib::misc::ord_f64::OrdF64;
use std::ops::Add;
use std::ops::AddAssign;
use std::ops::Mul;
use std::ops::Sub;
use std::ops::SubAssign;
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Default)]
pub struct PointT<T: Number> {
pub x: T,
pub y: T,
}
impl<T: Ord + Number> Ord for PointT<T> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.x.cmp(&other.x).then(self.y.cmp(&other.y))
}
}
impl<T: Ord + Number> PartialOrd for PointT<T> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.cmp(other).into()
}
}
impl<T: Number> PointT<T> {
pub fn new(x: T, y: T) -> Self {
Self { x, y }
}
pub fn dist2(&self, p2: &PointT<T>) -> T {
let dx = self.x - p2.x;
let dy = self.y - p2.y;
dx * dx + dy * dy
}
pub fn side(&self) -> i32 {
if self.y > T::ZERO || (self.y == T::ZERO && self.x >= T::ZERO) {
return 0;
}
1
}
pub fn dist_manh(&self, p2: &PointT<T>) -> T {
let dx = self.x - p2.x;
let dy = self.y - p2.y;
let dx_abs = if dx < T::ZERO { T::ZERO - dx } else { dx };
let dy_abs = if dy < T::ZERO { T::ZERO - dy } else { dy };
dx_abs + dy_abs
}
pub fn angle_to(&self, other: &PointT<T>) -> OrdF64
where
f64: From<T>,
{
let dy = other.y - self.y;
let dx = other.x - self.x;
OrdF64(f64::atan2(dy.into(), dx.into()))
}
pub fn swap_x_y(&self) -> Self {
Self::new(self.y, self.x)
}
pub fn vect_mul(p1: &PointT<T>, p2: &PointT<T>, p3: &PointT<T>) -> T {
(p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x)
}
pub fn scal_mul(p1: &PointT<T>, p2: &PointT<T>, p3: &PointT<T>) -> T {
Self::scal_mul2(&(*p2 - *p1), &(*p3 - *p1))
}
pub fn scal_mul2(p1: &PointT<T>, p2: &PointT<T>) -> T {
p1.x * p2.x + p1.y * p2.y
}
pub fn vect_mul2(p1: &PointT<T>, p2: &PointT<T>) -> T {
p1.x * p2.y - p1.y * p2.x
}
pub fn apply_shift(&self, shift: &Shift) -> Self {
Self {
x: self.x + T::from_i32(shift.dx),
y: self.y + T::from_i32(shift.dy),
}
}
pub fn shift(&self, dx: T, dy: T) -> Self {
Self {
x: self.x + dx,
y: self.y + dy,
}
}
pub fn scale(&self, coef: T) -> Self {
Self {
x: self.x * coef,
y: self.y * coef,
}
}
pub fn index_vec2d<'a, Elem>(&self, arr: &'a [Vec<Elem>]) -> Option<&'a Elem> {
if self.x >= T::ZERO
&& self.x < T::from_i32(arr.len() as i32)
&& self.y >= T::ZERO
&& self.y < T::from_i32(arr[T::to_i32(self.x) as usize].len() as i32)
{
let x = T::to_i32(self.x) as usize;
let y = T::to_i32(self.y) as usize;
Some(&arr[x][y])
} else {
None
}
}
pub fn index_arr2d<'a, Elem>(&self, arr: &'a Array2D<Elem>) -> Option<&'a Elem>
where
Elem: Clone,
{
if self.x >= T::ZERO
&& self.x < T::from_i32(arr.len() as i32)
&& self.y >= T::ZERO
&& self.y < T::from_i32(arr[T::to_i32(self.x) as usize].len() as i32)
{
let x = T::to_i32(self.x) as usize;
let y = T::to_i32(self.y) as usize;
Some(&arr[x][y])
} else {
None
}
}
pub fn rotate_ccw(&self) -> Self {
Self::new(T::ZERO - self.y, self.x)
}
pub const ZERO: PointT<T> = PointT {
x: T::ZERO,
y: T::ZERO,
};
pub fn conv_float(&self) -> PointT<OrdF64> {
PointT::new(OrdF64(self.x.to_f64()), OrdF64(self.y.to_f64()))
}
}
impl<T> Add for PointT<T>
where
T: Number,
{
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self::new(self.x + rhs.x, self.y + rhs.y)
}
}
impl<T> AddAssign for PointT<T>
where
T: Number,
{
fn add_assign(&mut self, rhs: Self) {
self.x += rhs.x;
self.y += rhs.y;
}
}
impl<T> Sub for PointT<T>
where
T: Number,
{
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self::new(self.x - rhs.x, self.y - rhs.y)
}
}
impl<T> SubAssign for PointT<T>
where
T: Number,
{
fn sub_assign(&mut self, rhs: Self) {
self.x -= rhs.x;
self.y -= rhs.y;
}
}
impl<T> Readable for PointT<T>
where
T: Number + Readable,
{
fn read(input: &mut Input) -> Self {
let x = input.read();
let y = input.read();
Self { x, y }
}
}
impl<T> Writable for PointT<T>
where
T: Number + Writable,
{
fn write(&self, output: &mut Output) {
self.x.write(output);
output.put(b' ');
self.y.write(output);
}
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct PointWithIdT<T: Number> {
pub p: PointT<T>,
id: u32,
}
impl<T> PointWithIdT<T>
where
T: Number,
{
pub fn new(p: PointT<T>, id: usize) -> Self {
Self { p, id: id as u32 }
}
pub fn id(&self) -> usize {
self.id as usize
}
}
impl PointWithIdT<OrdF64> {
pub fn dist(&self, other: &Self) -> OrdF64 {
self.p.dist2(&other.p).sqrt()
}
}
impl PointT<OrdF64> {
pub fn rotate_ccw_angle(&self, angle: OrdF64) -> Self {
let cos = f!(angle.0.cos());
let sin = f!(angle.0.sin());
let x = self.x * cos - self.y * sin;
let y = self.y * cos + self.x * sin;
Self { x, y }
}
}
impl Mul<OrdF64> for PointT<OrdF64> {
type Output = PointT<OrdF64>;
fn mul(self, rhs: OrdF64) -> Self::Output {
Self {
x: self.x * rhs,
y: self.y * rhs,
}
}
}
}
pub mod polygon {
use crate::algo_lib::geometry::line::Line;
use crate::algo_lib::geometry::point::PointT;
use crate::algo_lib::geometry::segment::SegmentT;
use crate::algo_lib::io::input::Input;
use crate::algo_lib::io::input::Readable;
use crate::algo_lib::misc::num_traits::HasConstants;
use crate::algo_lib::misc::num_traits::Number;
use crate::algo_lib::misc::num_traits::Signum;
use crate::algo_lib::misc::ord_f64::OrdF64;
use std::fmt::Debug;
use std::fmt::Formatter;
pub struct PolygonT<T>
where
T: Number,
{
points: Vec<PointT<T>>,
}
pub struct PolygonEdgeIter<'a, T>
where
T: Number,
{
polygon: &'a PolygonT<T>,
pos: u32,
}
impl<T> PolygonT<T>
where
T: Number + Ord,
{
pub fn new(mut points: Vec<PointT<T>>) -> Self {
assert_ne!(points.len(), 0);
points.push(points[0]);
Self { points }
}
pub fn new_rect(start: PointT<T>, end: PointT<T>) -> Self {
Self::new(vec![
start,
PointT::new(end.x, start.y),
end,
PointT::new(start.x, end.y),
])
}
pub fn points(&self) -> &[PointT<T>] {
&self.points[0..self.points.len() - 1]
}
pub fn edges(&self) -> PolygonEdgeIter<T> {
PolygonEdgeIter {
polygon: self,
pos: 0,
}
}
pub fn min_x(&self) -> T {
self.points.iter().map(|p| p.x).min().unwrap()
}
pub fn max_x(&self) -> T {
self.points.iter().map(|p| p.x).max().unwrap()
}
pub fn min_y(&self) -> T {
self.points.iter().map(|p| p.y).min().unwrap()
}
pub fn max_y(&self) -> T {
self.points.iter().map(|p| p.y).max().unwrap()
}
pub fn area_signed(&self) -> T {
let mut res = T::ZERO;
for edge in self.edges() {
res += edge.from.x * edge.to.y - edge.to.x * edge.from.y;
}
res / T::TWO
}
pub fn area_x2(&self) -> T {
let mut res = T::ZERO;
for edge in self.edges() {
res += edge.from.x * edge.to.y - edge.to.x * edge.from.y;
}
if res < T::ZERO {
T::ZERO - res
} else {
res
}
}
// To the left of [from] --> [to]
pub fn cut(&self, from: PointT<T>, to: PointT<T>) -> PolygonT<OrdF64>
where
f64: From<T>,
{
let l1 = Line::new(&from.conv_float(), &to.conv_float());
let mut pts = vec![];
for s in self.edges() {
let (cur, next) = (s.from, s.to);
let v_cur = PointT::vect_mul(&from, &to, &cur);
let v_next = PointT::vect_mul(&from, &to, &next);
if v_cur >= T::ZERO {
pts.push(cur.conv_float());
}
if v_cur != T::ZERO && v_next != T::ZERO && v_cur.signum() != v_next.signum() {
let l2 = Line::new(&cur.conv_float(), &next.conv_float());
let intersection = l1.intersect(&l2).unwrap();
pts.push(intersection);
}
}
PolygonT::new(pts)
}
fn center_of_triangle(
p1: PointT<OrdF64>,
p2: PointT<OrdF64>,
p3: PointT<OrdF64>,
) -> PointT<OrdF64> {
let x = (p1.x + p2.x + p3.x) / OrdF64(3.0);
let y = (p1.y + p2.y + p3.y) / OrdF64(3.0);
PointT::new(x, y)
}
pub fn center_of_gravity(&self) -> PointT<OrdF64> {
let mut sum_sq = OrdF64(0.0);
let mut res = PointT::ZERO;
for seg in self.edges() {
let (cur, next) = (seg.from.conv_float(), seg.to.conv_float());
let vmul = cur.x * next.y - cur.y * next.x;
sum_sq += vmul;
let center = Self::center_of_triangle(PointT::ZERO, cur, next);
res += PointT::new(center.x * vmul, center.y * vmul);
}
assert!(sum_sq > OrdF64::ZERO);
res.x /= sum_sq;
res.y /= sum_sq;
res
}
}
impl<'a, T> Iterator for PolygonEdgeIter<'a, T>
where
T: Number + Ord,
{
type Item = SegmentT<T>;
fn next(&mut self) -> Option<Self::Item> {
let first = self.polygon.points[self.pos as usize];
self.pos += 1;
let second = self.polygon.points.get(self.pos as usize);
second.map(|&second| SegmentT::new(first, second))
}
}
impl<T> Readable for PolygonT<T>
where
T: Number + Readable + Ord,
{
fn read(input: &mut Input) -> Self {
let n = input.usize();
Self::new(input.vec::<PointT<T>>(n))
}
}
impl<T> Debug for PolygonT<T>
where
T: Number + Ord,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
writeln!(f, "[")?;
for (id, p) in self.points().iter().enumerate() {
writeln!(f, " {}:: ({:?}; {:?})", id, p.x, p.y)?;
}
writeln!(f, "]")
}
}
impl PolygonT<OrdF64> {
pub fn area(&self) -> OrdF64 {
self.area_x2() / OrdF64::TWO
}
}
}
pub mod segment {
use std::cmp::Ordering;
use crate::algo_lib::geometry::direction::DirectionT;
use crate::algo_lib::geometry::line::Line;
use crate::algo_lib::geometry::point::PointT;
use crate::algo_lib::geometry::segment_intersection::inside_bounding_box;
use crate::algo_lib::misc::num_traits::HasConstants;
use crate::algo_lib::misc::num_traits::Number;
use crate::algo_lib::misc::ord_f64::OrdF64;
#[derive(Copy, Clone, Debug)]
pub struct SegmentT<T>
where
T: Number,
{
pub from: PointT<T>,
pub to: PointT<T>,
}
impl<T> SegmentT<T>
where
T: Number + Ord,
{
pub fn new(from: PointT<T>, to: PointT<T>) -> Self {
Self { from, to }
}
pub fn dir(&self) -> DirectionT<T> {
DirectionT::new(self.from, self.to)
}
///
/// 1 means "[p] is to the left from [self.from] -> [self.to] ray"
/// 0 means "on the same line"
///
pub fn to_the_left(&self, p: &PointT<T>) -> i32 {
let v_mul = PointT::<T>::vect_mul(&self.from, &self.to, p);
match v_mul.cmp(&T::ZERO) {
Ordering::Less => -1,
Ordering::Equal => 0,
Ordering::Greater => 1,
}
}
}
impl SegmentT<OrdF64> {
pub fn to_line(&self) -> Line {
Line::new(&self.from, &self.to)
}
pub fn contains(&self, p: &PointT<OrdF64>) -> bool {
// TODO: should use eps?
inside_bounding_box(self, p) && PointT::vect_mul(&self.from, &self.to, p) == OrdF64::ZERO
}
pub fn len2(&self) -> OrdF64 {
self.from.dist2(&self.to)
}
pub fn len(&self) -> OrdF64 {
self.len2().sqrt()
}
}
}
pub mod segment_intersection {
use crate::algo_lib::geometry::point::PointT;
use crate::algo_lib::geometry::segment::SegmentT;
use crate::algo_lib::misc::ord_f64::OrdF64;
use std::cmp::max;
use std::cmp::min;
type Point = PointT<OrdF64>;
type Segment = SegmentT<OrdF64>;
fn inside_one_dim(range: (OrdF64, OrdF64), val: OrdF64) -> bool {
min(range.0, range.1) - OrdF64::EPS <= val && val <= max(range.0, range.1) + OrdF64::EPS
}
pub fn inside_bounding_box(seg: &Segment, p: &Point) -> bool {
inside_one_dim((seg.from.x, seg.to.x), p.x) && inside_one_dim((seg.from.y, seg.to.y), p.y)
}
pub fn segment_intersection(seg1: &Segment, seg2: &Segment) -> Option<Point> {
seg1.to_line()
.intersect(&seg2.to_line())
.filter(|&inter| inside_bounding_box(seg1, &inter) && inside_bounding_box(seg2, &inter))
}
}
}
pub mod io {
pub mod input {
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 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) -> f64 {
self.read_string().parse().unwrap()
}
pub fn f64(&mut self) -> f64 {
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);
}
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).unwrap_or_else(|_| panic!("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 {
OUTPUT = Some(Output::new(output));
}
let input = match io.input {
TaskIoType::Std => {
let sin = std::io::stdin();
Input::new(Box::new(sin))
}
TaskIoType::File(file) => Input::new_file(file),
};
run(input)
}
}
}
pub mod iters {
pub mod shifts {
#[derive(Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
pub struct Shift {
pub dx: i32,
pub dy: i32,
}
impl Shift {
pub fn rev(&self) -> Self {
Self {
dx: -self.dx,
dy: -self.dy,
}
}
}
// x goes down
// y goes right
pub const SHIFT_DOWN: Shift = Shift { dx: 1, dy: 0 };
pub const SHIFT_UP: Shift = Shift { dx: -1, dy: 0 };
pub const SHIFT_RIGHT: Shift = Shift { dx: 0, dy: 1 };
pub const SHIFT_LEFT: Shift = Shift { dx: 0, dy: -1 };
pub const SHIFTS_4: [Shift; 4] = [SHIFT_DOWN, SHIFT_LEFT, SHIFT_UP, SHIFT_RIGHT];
pub const SHIFTS_8: [Shift; 8] = [
SHIFT_DOWN,
SHIFT_LEFT,
SHIFT_UP,
SHIFT_RIGHT,
Shift { dx: -1, dy: -1 },
Shift { dx: -1, dy: 1 },
Shift { dx: 1, dy: -1 },
Shift { dx: 1, dy: 1 },
];
pub const SHIFTS_9: [Shift; 9] = [
SHIFT_DOWN,
SHIFT_LEFT,
SHIFT_UP,
SHIFT_RIGHT,
Shift { dx: -1, dy: -1 },
Shift { dx: -1, dy: 1 },
Shift { dx: 1, dy: -1 },
Shift { dx: 1, dy: 1 },
Shift { dx: 0, dy: 0 },
];
pub fn shift_by_nswe(c: u8) -> Shift {
match c {
b'S' | b's' => SHIFT_DOWN,
b'N' | b'n' => SHIFT_UP,
b'E' | b'e' => SHIFT_RIGHT,
b'W' | b'w' => SHIFT_LEFT,
_ => panic!("Unexpected direction!"),
}
}
pub fn shift_by_uldr(c: u8) -> Shift {
match c {
b'D' | b'd' => SHIFT_DOWN,
b'U' | b'u' => SHIFT_UP,
b'R' | b'r' => SHIFT_RIGHT,
b'L' | b'l' => SHIFT_LEFT,
_ => panic!("Unexpected direction!"),
}
}
}
}
pub mod math {
pub mod gcd {
use crate::algo_lib::misc::num_traits::Number;
#[allow(dead_code)]
fn extended_gcd(a: i64, b: i64, x: &mut i64, y: &mut i64) -> i64 {
if a == 0 {
*x = 0;
*y = 1;
return b;
}
let mut x1 = 0;
let mut y1 = 0;
let d = extended_gcd(b % a, a, &mut x1, &mut y1);
*x = y1 - (b / a) * x1;
*y = x1;
d
}
///
///
/// Find any solution to equation A*x + B*y = C
///
/// Returns [false] if [C] is not divisible by gcd(A, B)
///
#[allow(dead_code)]
pub fn diophantine(a: i64, b: i64, c: i64, x0: &mut i64, y0: &mut i64, g: &mut i64) -> bool {
*g = extended_gcd(a.abs(), b.abs(), x0, y0);
if c % *g != 0 {
return false;
}
*x0 *= c / *g;
*y0 *= c / *g;
if a < 0 {
*x0 *= -1;
}
if b < 0 {
*y0 *= -1;
}
true
}
#[allow(dead_code)]
pub fn gcd<T>(x: T, y: T) -> T
where
T: Number + std::ops::Rem<Output = T>,
{
if x == T::ZERO {
y
} else {
gcd(y % x, x)
}
}
pub fn lcm<T>(x: T, y: T) -> T
where
T: Number + std::ops::Rem<Output = T>,
{
x / gcd(x, y) * y
}
}
}
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 num_traits {
use std::cmp::Ordering;
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 ConvSimple<T> {
fn from_i32(val: i32) -> T;
fn to_i32(self) -> i32;
fn to_f64(self) -> f64;
}
pub trait Signum {
fn signum(&self) -> i32;
}
pub trait Number:
Copy
+ Add<Output = Self>
+ AddAssign
+ Sub<Output = Self>
+ SubAssign
+ Mul<Output = Self>
+ MulAssign
+ Div<Output = Self>
+ DivAssign
+ PartialOrd
+ PartialEq
+ HasConstants<Self>
+ Default
+ Debug
+ Sized
+ ConvSimple<Self>
{
}
impl<
T: Copy
+ Add<Output = Self>
+ AddAssign
+ Sub<Output = Self>
+ SubAssign
+ Mul<Output = Self>
+ MulAssign
+ Div<Output = Self>
+ DivAssign
+ PartialOrd
+ PartialEq
+ HasConstants<Self>
+ Default
+ Debug
+ Sized
+ ConvSimple<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 ConvSimple<$t> for $t {
fn from_i32(val: i32) -> $t {
val as $t
}
fn to_i32(self) -> i32 {
self as i32
}
fn to_f64(self) -> f64 {
self as f64
}
}
};
}
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 ConvSimple<Self> for f64 {
fn from_i32(val: i32) -> Self {
val as f64
}
fn to_i32(self) -> i32 {
self as i32
}
fn to_f64(self) -> f64 {
self
}
}
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;
}
impl<T: Number + Ord> Signum for T {
fn signum(&self) -> i32 {
match self.cmp(&T::ZERO) {
Ordering::Greater => 1,
Ordering::Less => -1,
Ordering::Equal => 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::ConvSimple;
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(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 PartialOrd for OrdF64 {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}
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 ConvSimple<Self> for OrdF64 {
fn from_i32(val: i32) -> Self {
Self(val as f64)
}
fn to_i32(self) -> i32 {
self.0 as i32
}
fn to_f64(self) -> f64 {
self.0
}
}
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)
}
}
}
}
}
fn main() {
crate::solution::submit();
}
这程序好像有点Bug,我给组数据试试?
详细
Test #1:
score: 100
Accepted
time: 0ms
memory: 2112kb
input:
0 1 0 1 ([-1,1,0]^[-1,-1,1])
output:
0.5
result:
ok found '0.5000000', expected '0.5000000', error '0.0000000'
Test #2:
score: 0
Accepted
time: 0ms
memory: 2148kb
input:
-5 10 -10 5 ((!([1,2,-3]&[10,3,-2]))^([-2,3,1]|[5,-2,7]))
output:
70.45169340463458
result:
ok found '70.4516934', expected '70.4516934', error '0.0000000'
Test #3:
score: 0
Accepted
time: 0ms
memory: 2200kb
input:
0 1 -1 1 ([1,1,1]&[-1,-1,-1])
output:
0
result:
ok found '0.0000000', expected '0.0000000', error '-0.0000000'
Test #4:
score: 0
Accepted
time: 0ms
memory: 2056kb
input:
0 1000 0 1000 (([1,-1,0]&[-1000,999,999])&([1,0,-998]&[0,1,-998]))
output:
0.0004999999655410647
result:
ok found '0.0005000', expected '0.0005000', error '0.0000000'
Test #5:
score: 0
Accepted
time: 5ms
memory: 3176kb
input:
-725 165 643 735 ((((!(([22,15,137]|(!([23,-5,-41]^(!([2,25,-515]&[-37,10,487])))))&(!(([25,24,47]^([-24,21,-114]^[19,-7,79]))^[4,20,241]))))^(!((!((!(([30,-1,474]^([14,17,155]^[-31,-6,-153]))|[-15,-15,108]))|(([-26,-11,421]&[-15,-3,-224])&[14,-3,458])))^[9,20,-404])))^(!((!((!(([14,-6,-464]^[-11,8,...
output:
47063.33485244143
result:
ok found '47063.3348524', expected '47063.3348524', error '0.0000000'
Test #6:
score: 0
Accepted
time: 5ms
memory: 3200kb
input:
767 957 738 941 ((!(((!([3,-3,507]^[-30,-10,425]))^[-6,7,643])^((!((!([-11,0,450]^[21,17,-65]))&(!([17,0,64]^[-11,0,804]))))|[-31,10,-687])))&((!(([-34,12,-527]^(!([17,-14,-219]^(!([13,-27,-105]^(!([18,-47,-110]&(!([-9,-20,-455]^[-18,26,-228])))))))))^([-4,0,144]^[10,1,396])))^((!((!([35,0,-221]&[-5...
output:
36999.05865566316
result:
ok found '36999.0586557', expected '36999.0586557', error '0.0000000'
Test #7:
score: 0
Accepted
time: 199ms
memory: 11816kb
input:
-513 213 -733 114 (!((!((!((((!([2,16,-57]|[15,40,-272]))^((!(([0,26,315]|[5,-4,-336])^(!([-12,2,218]&([17,-16,-730]&[-7,3,-263])))))^[18,-7,29]))^[5,30,-126])^((!(((!((([8,9,406]^(!([-26,6,63]^[-38,-25,108])))^(([-9,20,220]^(!([-2,-27,213]^[29,16,-269])))|[-12,-4,-586]))^([30,0,-443]|(!((!([-17,0,3...
output:
295728.6081036077
result:
ok found '295728.6081036', expected '295728.6081036', error '0.0000000'
Test #8:
score: 0
Accepted
time: 76ms
memory: 11932kb
input:
-517 -379 -789 477 (((!((!(([1,-12,191]^(!(((!([32,0,89]^[-35,6,33]))^[-3,6,-293])^[20,-39,77])))^(([16,15,-285]^[15,-7,430])^([20,3,-95]|(!((!(([-15,-27,339]^[-11,-13,221])^[33,28,596]))|([-17,21,402]^[22,16,90])))))))&(!((!((!([12,-1,-279]^[-30,-13,224]))^[-29,24,-33]))^([31,-19,288]^(!((!([-1,26,...
output:
107150.6048796972
result:
ok found '107150.6048797', expected '107150.6048797', error '0.0000000'
Test #9:
score: 0
Accepted
time: 2ms
memory: 2328kb
input:
-477 275 -266 519 (!((!((!((!([-1,3,162]|[-32,16,269]))&(!(((((([-31,7,114]^([-12,7,-163]^[23,-10,159]))|(!(([0,-16,114]^[-33,15,-190])|(!([1,-22,308]^[-31,13,316])))))^((!([-12,29,-22]^(([23,15,-8]^[0,15,46])^[6,15,356])))^[22,13,-163]))^([18,17,487]^[28,23,143]))|(!(((!((!(([7,-45,-583]&([31,2,-22...
output:
335169.31051751616
result:
ok found '335169.3105175', expected '335169.3105175', error '0.0000000'
Test #10:
score: 0
Accepted
time: 2ms
memory: 2876kb
input:
175 624 -835 683 (!(((!(([-32,30,-478]^[23,4,-120])^[28,33,413]))|(!((!((!((!([-15,-5,0]^(!((!(((!([0,-32,90]^[-9,-22,-7]))^[-10,-35,344])|(!([1,11,-235]|[-31,-6,-344]))))^(!((!([-15,0,-90]|[-17,-10,-153]))^[-1,6,-8]))))))^(!([8,-6,302]^[-2,4,91]))))|([13,28,-70]^[16,-11,-74])))^(((((!((!((([-5,8,45...
output:
411470.3585049434
result:
ok found '411470.3585049', expected '411470.3585049', error '0.0000000'
Test #11:
score: 0
Accepted
time: 36ms
memory: 4076kb
input:
-1000 1000 -1000 1000 ([1,0,-1000]^([0,1,-1000]^([1,0,-980]^([0,1,-980]^([1,0,-960]^([0,1,-960]^([1,0,-940]^([0,1,-940]^([1,0,-920]^([0,1,-920]^([1,0,-900]^([0,1,-900]^([1,0,-880]^([0,1,-880]^([1,0,-860]^([0,1,-860]^([1,0,-840]^([0,1,-840]^([1,0,-820]^([0,1,-820]^([1,0,-800]^([0,1,-800]^([1,0,-780]^...
output:
2000000
result:
ok found '2000000.0000000', expected '2000000.0000000', error '0.0000000'
Test #12:
score: 0
Accepted
time: 38ms
memory: 4408kb
input:
-500 500 -500 500 ([2,-3,-1000]^([2,3,-1000]^([2,-3,-980]^([2,3,-980]^([2,-3,-960]^([2,3,-960]^([2,-3,-940]^([2,3,-940]^([2,-3,-920]^([2,3,-920]^([2,-3,-900]^([2,3,-900]^([2,-3,-880]^([2,3,-880]^([2,-3,-860]^([2,3,-860]^([2,-3,-840]^([2,3,-840]^([2,-3,-820]^([2,3,-820]^([2,-3,-800]^([2,3,-800]^([2,-...
output:
539999.9999999304
result:
ok found '539999.9999999', expected '540000.0000000', error '0.0000000'
Test #13:
score: 0
Accepted
time: 5ms
memory: 3056kb
input:
-1000 1000 -1000 1000 ([-57,281,0]^([478,81,0]^([-362,995,0]^([-339,614,0]^([491,769,0]^([673,486,0]^([-637,374,0]^([-204,383,0]^([-509,859,0]^([-973,757,0]^([-707,648,0]^([-792,409,0]^([-944,621,0]^([446,21,0]^([-553,473,0]^([795,704,0]^([-821,992,0]^([89,47,0]^([771,332,0]^([-845,259,0]^([271,867,...
output:
1823923.8971529505
result:
ok found '1823923.8971530', expected '1823923.8971530', error '0.0000000'
Test #14:
score: 0
Accepted
time: 0ms
memory: 2120kb
input:
-1000 1000 -1000 1000 (([-27,-20,-237]^((([31,17,247]^[-4,-23,-917])^(![8,21,-342]))^((([-17,2,-281]&[-26,-31,186])|[31,-21,-697])|[-18,8,-512])))&[-5,19,-104])
output:
420530.7345409404
result:
ok found '420530.7345409', expected '420530.7345409', error '0.0000000'
Test #15:
score: 0
Accepted
time: 79ms
memory: 7720kb
input:
-1000 1000 -1000 1000 ((((!(((([31,17,247]^[-4,-23,-917])^(![8,21,-342]))^((([-17,2,-281]&[-26,-31,186])|[31,-21,-697])|[-18,8,-512]))^((!((!(!((([12,23,237]|[913,22,925])^[-14,11,-956])^[-9,-10,818])))|((([3,1,-213]^[-296,-13,171])&(!(!((!((!([-10,6,636]^[17,19,-546]))^([28,28,-698]|[-14,-4,-295]))...
output:
1479667.4407859659
result:
ok found '1479667.4407860', expected '1479667.4407860', error '0.0000000'
Test #16:
score: 0
Accepted
time: 218ms
memory: 11732kb
input:
-1000 1000 -1000 1000 (((((((((((([-15,-2,9]^[-168,-28,507])^[-31,-23,293])^[23,-1,-290])^(([26,-4,869]^(([24,2,522]^[-10,5,-918])^[-22,5,50]))^[16,-827,-276]))^(([-1,-24,-651]^([16,15,-332]^[-722,29,-330]))^([-19,-23,14]^[12,-18,289])))^(((([6,-29,803]^[8,-8,50])^((([9,-7,-112]^([23,-29,-827]^[-12,...
output:
1945479.9574398734
result:
ok found '1945479.9574399', expected '1945479.9574399', error '0.0000000'
Test #17:
score: 0
Accepted
time: 1ms
memory: 2420kb
input:
0 1000 0 1000 (((((((([85,-100,0]^[21,-100,0])^[55,-100,0])^([29,-100,0]^([47,-100,0]^([78,-100,0]^([13,-100,0]^([100,-11,0]^[86,-100,0]))))))^(([48,-100,0]^[35,-100,0])^((([39,-100,0]^[98,-100,0])^([9,-100,0]^[100,-14,0]))^[100,-79,0])))^([12,-100,0]^[100,-100,0]))^((([20,-100,0]^([100,-64,0]^([100...
output:
500000
result:
ok found '500000.0000000', expected '500000.0000000', error '0.0000000'
Test #18:
score: 0
Accepted
time: 30ms
memory: 4608kb
input:
0 100 0 100 (((([-85,1,0]^((([-21,1,0]^([-55,1,0]^(([-29,1,0]^[-47,1,0])^([-78,1,0]^[-13,1,0]))))^(([11,1,-100]^[-86,1,0])^[-48,1,0]))^([-35,1,0]^((((([-39,1,0]^([-98,1,0]^[-9,1,0]))^((([14,1,-100]^[79,1,-100])^[-12,1,0])^[100,1,-100]))^((([-20,1,0]^[64,1,-100])^(([60,1,-100]^([-1,1,0]^[41,1,-100]))...
output:
4987.314854974336
result:
ok found '4987.3148550', expected '4987.3148550', error '0.0000000'
Test #19:
score: 0
Accepted
time: 112ms
memory: 7300kb
input:
-500 1000 -500 1000 ((((((([2,-1,37]^[2,-1,1])^(([2,1,-55]^(([2,1,-29]^[2,1,-47])^[2,1,-78]))^([2,1,-13]^[0,1,-11])))^(((([2,1,-86]^([2,1,-48]^[2,-1,100]))^[2,-1,95])^[2,1,-98])^([2,1,-9]^([0,1,-14]^[0,1,-79]))))^([2,-1,88]^[0,1,-100]))^(([2,1,-20]^(([0,1,-64]^([2,-1,85]^[2,1,-1]))^(([2,-1,65]^([0,1...
output:
145000
result:
ok found '145000.0000000', expected '145000.0000000', error '0.0000000'
Test #20:
score: 0
Accepted
time: 1ms
memory: 3088kb
input:
0 1000 0 1000 (!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!...
output:
623640
result:
ok found '623640.0000000', expected '623640.0000000', error '0.0000000'
Test #21:
score: 0
Accepted
time: 26ms
memory: 4488kb
input:
-300 300 -300 300 ((([-199,200,0]&[299,-300,0])&([-1,-300,300]&[1,200,-200]))&([-1,-215,215]^((((([-1,-279,279]^[-1,-245,245])^(((((([-1,-271,271]^[-1,-253,253])^([-1,-222,222]^([-1,-287,287]^[289,-290,0])))^([-1,-214,214]^[-1,-252,252]))^(([-1,-265,265]^[-1,-261,261])^([-1,-202,202]^((([-1,-291,291...
output:
0.0000013889168676284314
result:
ok found '0.0000014', expected '0.0000014', error '0.0000000'
Test #22:
score: 0
Accepted
time: 0ms
memory: 2068kb
input:
0 1000 0 1000 (([-998,999,0]&[999,-1000,0])&[-1,-1,3])
output:
0.0000011272536619699736
result:
ok found '0.0000011', expected '0.0000011', error '0.0000000'
Extra Test:
score: 0
Extra Test Passed