├── rust ├── misc │ ├── extensions │ │ ├── mod.rs │ │ ├── with.rs │ │ └── option.rs │ ├── direction.rs │ ├── memo │ │ ├── mod.rs │ │ ├── test.rs │ │ ├── memoization_vec.rs │ │ ├── memoization_2d.rs │ │ ├── memoization_3d.rs │ │ ├── memoization_4d.rs │ │ ├── memoization_5d.rs │ │ └── memoization.rs │ ├── mod.rs │ ├── when.rs │ ├── transparent_wrapper.rs │ ├── owned_cell.rs │ ├── cards.rs │ ├── time_tracker.rs │ ├── run_parallel.rs │ ├── value_ref.rs │ ├── value.rs │ ├── hungarian_algorithm.rs │ ├── recursive_function.rs │ ├── random.rs │ └── dirs.rs ├── numbers │ ├── primes │ │ ├── mod.rs │ │ ├── sieve.rs │ │ └── prime.rs │ ├── num_traits │ │ ├── invertable.rs │ │ ├── field.rs │ │ ├── ring.rs │ │ ├── mod.rs │ │ ├── add_sub.rs │ │ ├── from_u8.rs │ │ ├── zero_one.rs │ │ ├── mul_div_rem.rs │ │ ├── as_index.rs │ │ ├── primitive.rs │ │ ├── wideable.rs │ │ ├── ord.rs │ │ ├── sign.rs │ │ └── bit_ops.rs │ ├── mod.rs │ ├── integer_sqrt.rs │ ├── gcd.rs │ ├── fwht.rs │ ├── number_ext.rs │ ├── interpolation.rs │ ├── num_utils.rs │ ├── multiplicative_function.rs │ ├── number_iterator.rs │ ├── mod_utils.rs │ ├── inf_int.rs │ ├── test.rs │ └── gauss.rs ├── io │ ├── mod.rs │ └── input_iter.rs ├── collections │ ├── md_arr │ │ └── mod.rs │ ├── vec_ext │ │ ├── mod.rs │ │ ├── default.rs │ │ ├── sorted.rs │ │ ├── transpose.rs │ │ ├── detuple.rs │ │ └── inc_dec.rs │ ├── iter_ext │ │ ├── mod.rs │ │ ├── collect.rs │ │ ├── find_count.rs │ │ ├── min_max.rs │ │ ├── interleave.rs │ │ └── cur_next.rs │ ├── slice_ext │ │ ├── mod.rs │ │ ├── indices.rs │ │ ├── consecutive_iter.rs │ │ ├── qty.rs │ │ ├── next_permutation.rs │ │ ├── compress.rs │ │ ├── reversed.rs │ │ └── bounds.rs │ ├── legacy_fill.rs │ ├── mod.rs │ ├── test.rs │ ├── min_max.rs │ ├── id.rs │ ├── dsu2d.rs │ ├── fast_clear_fenwick.rs │ ├── fenwick.rs │ ├── dsu.rs │ ├── divided_set.rs │ └── persistent_fenwick.rs ├── string │ ├── string_algorithms │ │ ├── mod.rs │ │ ├── prefix_function.rs │ │ ├── z_algorithm.rs │ │ └── palindromes.rs │ ├── mod.rs │ ├── slicelike.rs │ └── composite_slicelike.rs ├── graph │ ├── edges │ │ ├── bi_edge_trait.rs │ │ ├── weighted_edge_trait.rs │ │ ├── mod.rs │ │ ├── edge_trait.rs │ │ ├── flow_edge_trait.rs │ │ ├── edge_id.rs │ │ ├── edge.rs │ │ ├── bi_edge.rs │ │ ├── weighted_edge.rs │ │ ├── weighted_flow_edge.rs │ │ └── flow_edge.rs │ ├── edge.rs │ ├── mod.rs │ ├── flow_graph.rs │ ├── minimal_spanning_tree.rs │ ├── topological_sort.rs │ ├── all_distances.rs │ ├── dfs_order.rs │ ├── bridges.rs │ ├── distances.rs │ ├── edge_distances.rs │ ├── hl_decomposition.rs │ └── strongly_connected_components.rs ├── geometry │ ├── mod.rs │ ├── geometry_utils.rs │ ├── angle.rs │ ├── polygon.rs │ ├── ray.rs │ └── line.rs └── lib.rs ├── c++ ├── stl │ ├── myswap.cpp │ ├── pair.cpp │ ├── vector.cpp │ └── merge sort.cpp ├── dp_opt │ ├── dnc_opt.cpp │ ├── knuth_opt.cpp │ └── cht.cpp ├── data_stucture │ ├── fenwick.cpp │ ├── fenwick-RangeSum.cpp │ ├── eertree.cpp │ ├── seg_lazy.cpp │ └── Splay.cpp ├── math │ ├── exgcd_modinv.cpp │ ├── euler's_totient_function.cpp │ ├── chinese-remainder.cpp │ ├── karatsuba.cpp │ ├── point_in_poly.cpp │ ├── faulhaber's_formula.cpp │ ├── fft_double.cpp │ ├── ntt.cpp │ ├── convex_hull.cpp │ └── fft_long.cpp ├── graph │ ├── disjoint_set.cpp │ ├── Flow with Demands.cpp │ ├── scc.cpp │ ├── Centroid Decomposition.cpp │ ├── 2_sat.cpp │ ├── Minimum General Weighted Matching.cpp │ ├── bipartite-matching-hopcroft.cpp │ ├── bcc.cpp │ ├── MaximumFlow_Dinic.cpp │ ├── Edmonds Blossom by koosaga.cpp │ ├── kcm_mcmf.cpp │ ├── FAST Mincost Flow.cpp │ └── hungarian.cpp ├── string │ ├── z.cpp │ ├── manacher.cpp │ ├── suffix_array.cpp │ └── aho_corasick.cpp ├── settings │ └── sublime.cpp └── miscellaneous │ └── fastio.cpp ├── pdf └── cp_handbook.pdf ├── python ├── setup.py └── Math │ └── 64bit-fftmod.py ├── README.md └── LICENSE /rust/misc/extensions/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod option; 2 | pub mod with; 3 | -------------------------------------------------------------------------------- /rust/numbers/primes/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod factorize; 2 | pub mod prime; 3 | pub mod sieve; 4 | -------------------------------------------------------------------------------- /rust/io/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod input; 2 | pub mod input_iter; 3 | pub mod output; 4 | pub mod scan; 5 | -------------------------------------------------------------------------------- /c++/stl/myswap.cpp: -------------------------------------------------------------------------------- 1 | template void myswap(T &a, T &b) { 2 | T tmp = a; a = b; b = tmp; 3 | } -------------------------------------------------------------------------------- /pdf/cp_handbook.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongjun7/Competitive-Programming/HEAD/pdf/cp_handbook.pdf -------------------------------------------------------------------------------- /rust/collections/md_arr/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod arr2d; 2 | pub mod arr3d; 3 | pub mod arr4d; 4 | pub mod arr5d; 5 | -------------------------------------------------------------------------------- /c++/dp_opt/dnc_opt.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongjun7/Competitive-Programming/HEAD/c++/dp_opt/dnc_opt.cpp -------------------------------------------------------------------------------- /rust/misc/direction.rs: -------------------------------------------------------------------------------- 1 | #[derive(Copy, Clone)] 2 | pub enum Direction { 3 | Left, 4 | Right, 5 | } 6 | -------------------------------------------------------------------------------- /c++/dp_opt/knuth_opt.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hongjun7/Competitive-Programming/HEAD/c++/dp_opt/knuth_opt.cpp -------------------------------------------------------------------------------- /rust/string/string_algorithms/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod palindromes; 2 | pub mod prefix_function; 3 | pub mod z_algorithm; 4 | -------------------------------------------------------------------------------- /rust/graph/edges/bi_edge_trait.rs: -------------------------------------------------------------------------------- 1 | use crate::graph::edges::edge_trait::EdgeTrait; 2 | 3 | pub trait BiEdgeTrait: EdgeTrait {} 4 | -------------------------------------------------------------------------------- /rust/collections/vec_ext/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod default; 2 | pub mod detuple; 3 | pub mod inc_dec; 4 | pub mod sorted; 5 | pub mod transpose; 6 | -------------------------------------------------------------------------------- /python/setup.py: -------------------------------------------------------------------------------- 1 | from sys import stdin, stdout 2 | stdin, stdout = open('input.txt', 'r'), open('output.txt', 'w'); input = stdin.readline 3 | -------------------------------------------------------------------------------- /rust/numbers/num_traits/invertable.rs: -------------------------------------------------------------------------------- 1 | pub trait Invertable: Sized { 2 | type Output; 3 | 4 | fn inv(&self) -> Option; 5 | } 6 | -------------------------------------------------------------------------------- /rust/string/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod composite_slicelike; 2 | pub mod hash; 3 | pub mod slicelike; 4 | pub mod str; 5 | pub mod string_algorithms; 6 | -------------------------------------------------------------------------------- /rust/collections/iter_ext/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod collect; 2 | pub mod cur_next; 3 | pub mod find_count; 4 | pub mod interleave; 5 | pub mod min_max; 6 | -------------------------------------------------------------------------------- /rust/geometry/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod angle; 2 | pub mod geometry_utils; 3 | pub mod line; 4 | pub mod point; 5 | pub mod polygon; 6 | pub mod ray; 7 | pub mod segment; 8 | -------------------------------------------------------------------------------- /rust/collections/slice_ext/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod bounds; 2 | pub mod compress; 3 | pub mod consecutive_iter; 4 | pub mod indices; 5 | pub mod next_permutation; 6 | pub mod qty; 7 | pub mod reversed; 8 | -------------------------------------------------------------------------------- /rust/misc/memo/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod memoization; 2 | pub mod memoization_2d; 3 | pub mod memoization_3d; 4 | pub mod memoization_4d; 5 | pub mod memoization_5d; 6 | pub mod memoization_vec; 7 | #[cfg(test)] 8 | mod test; 9 | -------------------------------------------------------------------------------- /rust/collections/vec_ext/default.rs: -------------------------------------------------------------------------------- 1 | pub fn default_vec(len: usize) -> Vec { 2 | let mut v = Vec::with_capacity(len); 3 | for _ in 0..len { 4 | v.push(T::default()); 5 | } 6 | v 7 | } 8 | -------------------------------------------------------------------------------- /rust/numbers/num_traits/field.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::num_traits::mul_div_rem::MulDiv; 2 | use crate::numbers::num_traits::ring::Ring; 3 | 4 | pub trait Field: Ring + MulDiv {} 5 | 6 | impl Field for T {} 7 | -------------------------------------------------------------------------------- /rust/graph/edges/weighted_edge_trait.rs: -------------------------------------------------------------------------------- 1 | use crate::graph::edges::edge_trait::EdgeTrait; 2 | 3 | pub trait WeightedEdgeTrait: EdgeTrait { 4 | fn weight(&self) -> W; 5 | fn weight_mut(&mut self) -> &mut W; 6 | } 7 | -------------------------------------------------------------------------------- /rust/misc/extensions/with.rs: -------------------------------------------------------------------------------- 1 | pub trait With: Sized { 2 | fn with(self, f: F) -> R 3 | where 4 | F: (FnOnce(Self) -> R), 5 | { 6 | f(self) 7 | } 8 | } 9 | 10 | impl With for T {} 11 | -------------------------------------------------------------------------------- /rust/collections/vec_ext/sorted.rs: -------------------------------------------------------------------------------- 1 | pub trait Sorted { 2 | fn sorted(self) -> Self; 3 | } 4 | 5 | impl Sorted for Vec { 6 | fn sorted(mut self) -> Self { 7 | self.sort(); 8 | self 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /rust/collections/iter_ext/collect.rs: -------------------------------------------------------------------------------- 1 | pub trait IterCollect: Iterator + Sized { 2 | fn collect_vec(self) -> Vec { 3 | self.collect() 4 | } 5 | } 6 | 7 | impl + Sized> IterCollect for I {} 8 | -------------------------------------------------------------------------------- /c++/stl/pair.cpp: -------------------------------------------------------------------------------- 1 | class pii { 2 | public: 3 | int a, b; 4 | pii() { 5 | *this = pii(0, 0); 6 | } 7 | pii(int a, int b) : a(a), b(b) {} 8 | bool operator<(const pii &y)const{ 9 | if (a != y.a) return a < y.a; 10 | return b < y.b; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /rust/collections/slice_ext/indices.rs: -------------------------------------------------------------------------------- 1 | use std::ops::Range; 2 | 3 | pub trait Indices { 4 | fn indices(&self) -> Range; 5 | } 6 | 7 | impl Indices for [T] { 8 | fn indices(&self) -> Range { 9 | 0..self.len() 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /rust/misc/extensions/option.rs: -------------------------------------------------------------------------------- 1 | pub trait OptionExt: Sized { 2 | fn as_opt(&self) -> Option<&Self> { 3 | Some(self) 4 | } 5 | 6 | fn to_opt(self) -> Option { 7 | Some(self) 8 | } 9 | } 10 | 11 | impl OptionExt for T {} 12 | -------------------------------------------------------------------------------- /rust/lib.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::too_many_arguments)] 2 | #![allow(clippy::type_complexity)] 3 | #![allow(clippy::missing_safety_doc)] 4 | 5 | pub mod collections; 6 | pub mod geometry; 7 | pub mod graph; 8 | pub mod io; 9 | pub mod misc; 10 | pub mod numbers; 11 | pub mod string; 12 | -------------------------------------------------------------------------------- /rust/numbers/num_traits/ring.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::num_traits::add_sub::AddSub; 2 | use crate::numbers::num_traits::mul_div_rem::Multable; 3 | use crate::numbers::num_traits::zero_one::ZeroOne; 4 | 5 | pub trait Ring: AddSub + Multable + ZeroOne {} 6 | 7 | impl Ring for T {} 8 | -------------------------------------------------------------------------------- /rust/graph/edges/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod bi_edge; 2 | pub mod bi_edge_trait; 3 | pub mod bi_weighted_edge; 4 | pub mod edge; 5 | pub mod edge_id; 6 | pub mod edge_trait; 7 | pub mod flow_edge; 8 | pub mod flow_edge_trait; 9 | pub mod weighted_edge; 10 | pub mod weighted_edge_trait; 11 | pub mod weighted_flow_edge; 12 | -------------------------------------------------------------------------------- /rust/collections/vec_ext/transpose.rs: -------------------------------------------------------------------------------- 1 | pub trait TransposePairVec { 2 | fn transpose_pair_vec(self) -> Vec<(V, U)>; 3 | } 4 | 5 | impl TransposePairVec for Vec<(U, V)> { 6 | fn transpose_pair_vec(self) -> Vec<(V, U)> { 7 | self.into_iter().map(|(u, v)| (v, u)).collect() 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /rust/numbers/num_traits/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod add_sub; 2 | pub mod as_index; 3 | pub mod bit_ops; 4 | pub mod field; 5 | pub mod from_u8; 6 | pub mod invertable; 7 | pub mod mul_div_rem; 8 | pub mod ord; 9 | pub mod primitive; 10 | pub mod ring; 11 | pub mod sign; 12 | pub mod wideable; 13 | pub mod zero_one; 14 | pub mod real; 15 | -------------------------------------------------------------------------------- /rust/numbers/num_traits/add_sub.rs: -------------------------------------------------------------------------------- 1 | use std::ops::{Add, AddAssign, Sub, SubAssign}; 2 | 3 | pub trait Addable: Add + AddAssign + Copy {} 4 | impl + AddAssign + Copy> Addable for T {} 5 | 6 | pub trait AddSub: Addable + Sub + SubAssign {} 7 | impl + SubAssign> AddSub for T {} 8 | -------------------------------------------------------------------------------- /rust/misc/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod cards; 2 | pub mod direction; 3 | pub mod dirs; 4 | pub mod hungarian_algorithm; 5 | pub mod memo; 6 | pub mod owned_cell; 7 | pub mod random; 8 | pub mod recursive_function; 9 | pub mod run_parallel; 10 | pub mod time_tracker; 11 | pub mod transparent_wrapper; 12 | pub mod value; 13 | pub mod value_ref; 14 | pub mod when; 15 | mod extensions; 16 | -------------------------------------------------------------------------------- /c++/data_stucture/fenwick.cpp: -------------------------------------------------------------------------------- 1 | const int TSIZE = 100000; 2 | int tree[TSIZE + 1]; 3 | 4 | // Returns the sum from index 1 to p, inclusive 5 | int query(int p) { 6 | int ret = 0; 7 | for (; p > 0; p -= p & -p) ret += tree[p]; 8 | return ret; 9 | } 10 | 11 | // Adds val to element with index pos 12 | void add(int p, int val) { 13 | for (; p <= TSIZE; p += p & -p) tree[p] += val; 14 | } -------------------------------------------------------------------------------- /rust/collections/slice_ext/consecutive_iter.rs: -------------------------------------------------------------------------------- 1 | use std::iter::{Skip, Zip}; 2 | use std::slice::Iter; 3 | 4 | pub trait ConsecutiveIter { 5 | fn consecutive_iter(&self) -> Zip, Skip>>; 6 | } 7 | 8 | impl ConsecutiveIter for [T] { 9 | fn consecutive_iter(&self) -> Zip, Skip>> { 10 | self.iter().zip(self.iter().skip(1)) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /rust/collections/iter_ext/find_count.rs: -------------------------------------------------------------------------------- 1 | pub trait IterFindCount: Iterator + Sized { 2 | fn find(mut self, item: T) -> Option { 3 | self.position(|r| r == item) 4 | } 5 | fn count_eq(self, item: &T) -> usize { 6 | self.filter(|r| r == item).count() 7 | } 8 | } 9 | 10 | impl> IterFindCount for I {} 11 | -------------------------------------------------------------------------------- /rust/numbers/num_traits/from_u8.rs: -------------------------------------------------------------------------------- 1 | pub trait FromU8 { 2 | fn from_u8(val: u8) -> Self; 3 | } 4 | 5 | macro_rules! from_u8_impl { 6 | ($($t: ident)+) => {$( 7 | impl FromU8 for $t { 8 | fn from_u8(val: u8) -> Self { 9 | val as $t 10 | } 11 | } 12 | )+}; 13 | } 14 | 15 | from_u8_impl!(i128 i64 i32 i16 i8 isize u128 u64 u32 u16 u8 usize); 16 | -------------------------------------------------------------------------------- /rust/graph/edge.rs: -------------------------------------------------------------------------------- 1 | // pub trait EdgeFlags { 2 | // const BIDIRECTIONAL: bool; 3 | // const REVERSABLE: bool; 4 | // type Weight; 5 | // type Capacity; 6 | // type Id; 7 | // type Payload; 8 | // } 9 | // 10 | // pub struct Edge { 11 | // to: usize, 12 | // weight: EF::Weight, 13 | // capacity: EF::Capacity, 14 | // id: EF::Id, 15 | // payload: EF::Payload, 16 | // } 17 | -------------------------------------------------------------------------------- /rust/graph/edges/edge_trait.rs: -------------------------------------------------------------------------------- 1 | pub trait EdgeTrait: Clone { 2 | const REVERSABLE: bool; 3 | 4 | fn to(&self) -> usize; 5 | fn id(&self) -> usize; 6 | fn set_id(&mut self, id: usize); 7 | fn reverse_id(&self) -> usize; 8 | fn set_reverse_id(&mut self, reverse_id: usize); 9 | #[must_use] 10 | fn reverse_edge(&self, from: usize) -> Self; 11 | } 12 | 13 | pub trait BidirectionalEdgeTrait: EdgeTrait {} 14 | -------------------------------------------------------------------------------- /rust/misc/when.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! when { 3 | {$($cond: expr => $then: expr,)*} => { 4 | match () { 5 | $(_ if $cond => $then,)* 6 | _ => unreachable!(), 7 | } 8 | }; 9 | {$($cond: expr => $then: expr,)* else $(=>)? $else: expr,} => { 10 | match () { 11 | $(_ if $cond => $then,)* 12 | _ => $else, 13 | } 14 | }; 15 | } 16 | -------------------------------------------------------------------------------- /rust/graph/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod all_distances; 2 | pub mod bridges; 3 | pub mod dfs_order; 4 | pub mod distances; 5 | pub mod edge; 6 | pub mod edge_distances; 7 | pub mod edges; 8 | pub mod flow_graph; 9 | #[allow(clippy::module_inception)] 10 | pub mod graph; 11 | pub mod hl_decomposition; 12 | pub mod lca; 13 | pub mod max_flow; 14 | pub mod min_cost_flow; 15 | pub mod minimal_spanning_tree; 16 | pub mod strongly_connected_components; 17 | pub mod topological_sort; 18 | -------------------------------------------------------------------------------- /c++/math/exgcd_modinv.cpp: -------------------------------------------------------------------------------- 1 | /* find a pair (c,d) s.t. ac + bd = gcd(a,b) */ 2 | pair extended_gcd(long long a, long long b) { 3 | if (b == 0) return make_pair(1, 0); 4 | pair t = extended_gcd(b, a % b); 5 | return make_pair(t.second, t.first - t.second * (a / b)); 6 | } 7 | /* Find x in [0,m) s.t. ax ≡ gcd(a, m) (mod m) */ 8 | long long modinverse(long long a, long long m) { 9 | return (extended_gcd(a, m).first % m + m) % m; 10 | } 11 | -------------------------------------------------------------------------------- /rust/numbers/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod fwht; 2 | pub mod gauss; 3 | pub mod gcd; 4 | pub mod inf_int; 5 | pub mod integer_sqrt; 6 | pub mod interpolation; 7 | pub mod matrix; 8 | pub mod mod_int; 9 | pub mod mod_utils; 10 | pub mod multiplicative_function; 11 | pub mod num_traits; 12 | pub mod num_utils; 13 | pub mod number_ext; 14 | pub mod number_iterator; 15 | pub mod prime_fft; 16 | pub mod primes; 17 | pub mod rational; 18 | pub mod signed_big_int; 19 | #[cfg(test)] 20 | mod test; 21 | pub mod unsigned_big_int; 22 | -------------------------------------------------------------------------------- /rust/numbers/num_traits/zero_one.rs: -------------------------------------------------------------------------------- 1 | pub trait ZeroOne { 2 | fn zero() -> Self; 3 | fn one() -> Self; 4 | } 5 | 6 | macro_rules! zero_one_integer_impl { 7 | ($($t: ident)+) => {$( 8 | impl ZeroOne for $t { 9 | fn zero() -> Self { 10 | 0 11 | } 12 | 13 | fn one() -> Self { 14 | 1 15 | } 16 | } 17 | )+}; 18 | } 19 | 20 | zero_one_integer_impl!(i128 i64 i32 i16 i8 isize u128 u64 u32 u16 u8 usize); 21 | -------------------------------------------------------------------------------- /rust/collections/legacy_fill.rs: -------------------------------------------------------------------------------- 1 | // 1.50 2 | pub trait LegacyFill { 3 | fn legacy_fill(&mut self, val: T); 4 | } 5 | 6 | impl LegacyFill for [T] { 7 | fn legacy_fill(&mut self, val: T) { 8 | for el in self.iter_mut() { 9 | *el = val.clone(); 10 | } 11 | } 12 | } 13 | 14 | impl LegacyFill for Vec { 15 | fn legacy_fill(&mut self, val: T) { 16 | for el in self.iter_mut() { 17 | *el = val.clone(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /c++/math/euler's_totient_function.cpp: -------------------------------------------------------------------------------- 1 | const int MAXS = 40; 2 | 3 | int phi[MAXS + 1]; 4 | 5 | bool notPrime[MAXS + 1]; 6 | 7 | void Euler_Totient_Function(void) { 8 | for (int i = 1; i <= MAXS; i++) { 9 | phi[i] = i; 10 | } 11 | notPrime[1] = true; 12 | for (int i = 2; i <= MAXS; i++) { 13 | if (notPrime[i] == true) { 14 | continue; 15 | } 16 | phi[i] = (phi[i] / i) * (i - 1); 17 | for (int j = i + i; j <= MAXS; j += i) { 18 | notPrime[j] = true; 19 | phi[j] = (phi[j] / i) * (i - 1); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /rust/numbers/num_traits/mul_div_rem.rs: -------------------------------------------------------------------------------- 1 | use std::ops::{Div, DivAssign, Mul, MulAssign, Rem, RemAssign}; 2 | 3 | pub trait Multable: Mul + MulAssign + Copy {} 4 | impl + MulAssign + Copy> Multable for T {} 5 | 6 | pub trait MulDiv: Multable + Div + DivAssign {} 7 | impl + DivAssign> MulDiv for T {} 8 | 9 | pub trait MulDivRem: MulDiv + Rem + RemAssign {} 10 | impl + RemAssign> MulDivRem for T {} 11 | -------------------------------------------------------------------------------- /rust/collections/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod bit_set; 2 | pub mod default_map; 3 | pub mod divided_set; 4 | pub mod dsu; 5 | pub mod dsu2d; 6 | pub mod fast_clear_fenwick; 7 | pub mod fenwick; 8 | pub mod id; 9 | pub mod indexed_heap; 10 | pub mod iter_ext; 11 | pub mod legacy_fill; 12 | pub mod md_arr; 13 | pub mod min_max; 14 | pub mod multi_set; 15 | pub mod permutation; 16 | pub mod persistent_fenwick; 17 | pub mod segment_tree; 18 | pub mod slice_ext; 19 | #[cfg(test)] 20 | mod test; 21 | pub mod treap; 22 | pub mod treap_map; 23 | pub mod vec_ext; 24 | -------------------------------------------------------------------------------- /rust/misc/transparent_wrapper.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! transparent_wrapper { 3 | ($name: ident, $t: ty) => { 4 | pub struct $name($t); 5 | 6 | impl Deref for $name { 7 | type Target = $t; 8 | 9 | fn deref(&self) -> &Self::Target { 10 | &self.0 11 | } 12 | } 13 | 14 | impl DerefMut for $name { 15 | fn deref_mut(&mut self) -> &mut Self::Target { 16 | &mut self.0 17 | } 18 | } 19 | }; 20 | } 21 | -------------------------------------------------------------------------------- /rust/misc/owned_cell.rs: -------------------------------------------------------------------------------- 1 | use std::cell::UnsafeCell; 2 | 3 | pub struct OwnedCell(UnsafeCell); 4 | 5 | impl OwnedCell { 6 | pub fn new(val: T) -> Self { 7 | Self(UnsafeCell::new(val)) 8 | } 9 | 10 | pub unsafe fn as_ref<'a>(&self) -> &'a T { 11 | &*self.0.get() 12 | } 13 | 14 | pub unsafe fn as_mut<'a>(&self) -> &'a mut T { 15 | &mut *self.0.get() 16 | } 17 | 18 | pub unsafe fn replace(&self, new_val: T) -> T { 19 | std::mem::replace(self.as_mut(), new_val) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /rust/geometry/geometry_utils.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::num_traits::real::RealTrait; 2 | 3 | pub fn canonize_angle(angle: T) -> T { 4 | canonize_angle_base(angle, T::zero() - T::PI) 5 | } 6 | 7 | pub fn canonize_angle_base(angle: T, base: T) -> T { 8 | let two = T::one() + T::one(); 9 | let mut angle = angle; 10 | while angle < base - T::epsilon() { 11 | angle += T::PI * two; 12 | } 13 | while angle > base + T::PI * two - T::epsilon() { 14 | angle -= T::PI * two; 15 | } 16 | angle 17 | } 18 | -------------------------------------------------------------------------------- /rust/graph/edges/flow_edge_trait.rs: -------------------------------------------------------------------------------- 1 | use crate::graph::edges::edge_trait::EdgeTrait; 2 | use crate::graph::graph::Graph; 3 | use crate::numbers::num_traits::add_sub::AddSub; 4 | use crate::numbers::num_traits::zero_one::ZeroOne; 5 | 6 | pub trait FlowEdgeTrait: EdgeTrait { 7 | fn capacity(&self) -> C; 8 | fn capacity_mut(&mut self) -> &mut C; 9 | fn flow(&self, graph: &Graph) -> C; 10 | fn push_flow(&self, flow: C) -> (usize, usize, C) { 11 | (self.to(), self.reverse_id(), flow) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /rust/misc/cards.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::iter_ext::find_count::IterFindCount; 2 | use crate::string::str::Str; 3 | 4 | pub fn string_to_card(s: &Str) -> (usize, usize) { 5 | assert!(s.len() == 2); 6 | let rank = b"23456789TJQKA".iter().find(&s[0]).unwrap(); 7 | let suit = b"CDHS".iter().find(&s[1]).unwrap(); 8 | (rank, suit) 9 | } 10 | 11 | pub fn card_to_string(rank: usize, suit: usize) -> Str<'static> { 12 | let mut res = Str::with_capacity(2); 13 | res.push(b"23456789TJQKA"[rank]); 14 | res.push(b"CDHS"[suit]); 15 | res 16 | } 17 | -------------------------------------------------------------------------------- /rust/numbers/num_traits/as_index.rs: -------------------------------------------------------------------------------- 1 | pub trait AsIndex { 2 | fn from_index(idx: usize) -> Self; 3 | fn to_index(self) -> usize; 4 | } 5 | 6 | macro_rules! from_index_impl { 7 | ($($t: ident)+) => {$( 8 | impl AsIndex for $t { 9 | fn from_index(idx: usize) -> Self { 10 | idx as $t 11 | } 12 | 13 | fn to_index(self) -> usize { 14 | self as usize 15 | } 16 | } 17 | )+}; 18 | } 19 | 20 | from_index_impl!(i128 i64 i32 i16 i8 isize u128 u64 u32 u16 u8 usize); 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Competitive-Programming 2 | Resources for Competitive Programming 3 | 4 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 5 | 6 | ## Reference 7 | * https://e-maxx-eng.appspot.com/ 8 | * https://github.com/kcm1700/algorithms 9 | * https://github.com/ntopia/icpc-teamnote 10 | * https://github.com/wookayin/teamnote 11 | * https://github.com/jaehyunp/stanfordacm 12 | * https://github.com/albusmath/acm-icpc-template 13 | * https://github.com/tzupengwang/PECaveros 14 | * https://github.com/EgorKulikov/rust_algo -------------------------------------------------------------------------------- /rust/numbers/num_traits/primitive.rs: -------------------------------------------------------------------------------- 1 | pub trait Primitive: Copy { 2 | fn to(self) -> T; 3 | } 4 | 5 | macro_rules! primitive_one { 6 | ($t: ident, $($u: ident)+) => {$( 7 | impl Primitive<$u> for $t { 8 | fn to(self) -> $u { 9 | self as $u 10 | } 11 | } 12 | )+}; 13 | } 14 | 15 | macro_rules! primitive { 16 | ($($t: ident)+) => {$( 17 | primitive_one!($t, u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize); 18 | )+} 19 | } 20 | 21 | primitive!(u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize); 22 | -------------------------------------------------------------------------------- /c++/math/chinese-remainder.cpp: -------------------------------------------------------------------------------- 1 | // find x s.t. x === a[0] (mod n[0]) 2 | // === a[1] (mod n[1]) 3 | // ... 4 | // assumption: gcd(n[i], n[j]) = 1 5 | ll chinese_remainder(ll* a, ll* n, int size) { 6 | if (size == 1) return *a; 7 | ll tmp = modinverse(n[0], n[1]); 8 | ll tmp2 = (tmp * (a[1] - a[0]) % n[1] + n[1]) % n[1]; 9 | ll ora = a[1]; 10 | ll tgcd = gcd(n[0], n[1]); 11 | a[1] = a[0] + n[0] / tgcd * tmp2; 12 | n[1] *= n[0] / tgcd; 13 | ll ret = chinese_remainder(a + 1, n + 1, size - 1); 14 | n[1] /= n[0] / tgcd; 15 | a[1] = ora; 16 | return ret; 17 | } -------------------------------------------------------------------------------- /rust/numbers/num_traits/wideable.rs: -------------------------------------------------------------------------------- 1 | use std::convert::From; 2 | 3 | pub trait Wideable: Sized { 4 | type W: From; 5 | 6 | fn downcast(w: Self::W) -> Self; 7 | } 8 | 9 | macro_rules! wideable_impl { 10 | ($($t: ident $w: ident),+) => {$( 11 | impl Wideable for $t { 12 | type W = $w; 13 | 14 | fn downcast(w: Self::W) -> Self { 15 | w as $t 16 | } 17 | } 18 | )+}; 19 | } 20 | 21 | wideable_impl!(i128 i128, i64 i128, i32 i64, i16 i32, i8 i16, isize isize, u128 u128, u64 u128, u32 u64, u16 u32, u8 u16, usize usize); 22 | -------------------------------------------------------------------------------- /rust/collections/slice_ext/qty.rs: -------------------------------------------------------------------------------- 1 | pub trait Qty { 2 | fn qty_bound(&self, bound: usize) -> Vec; 3 | fn qty(&self) -> Vec; 4 | } 5 | 6 | impl Qty for [usize] { 7 | fn qty_bound(&self, bound: usize) -> Vec { 8 | let mut res = vec![0; bound]; 9 | for i in self.iter() { 10 | res[*i] += 1; 11 | } 12 | res 13 | } 14 | 15 | fn qty(&self) -> Vec { 16 | if self.is_empty() { 17 | Vec::new() 18 | } else { 19 | self.qty_bound(self.iter().max().unwrap() + 1) 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /rust/string/slicelike.rs: -------------------------------------------------------------------------------- 1 | use std::ops::{Index, IndexMut}; 2 | 3 | pub trait Slicelike: Index 4 | where 5 | Self::Output: Sized, 6 | { 7 | fn len(&self) -> usize; 8 | fn is_empty(&self) -> bool { 9 | self.len() == 0 10 | } 11 | } 12 | 13 | impl Slicelike for [T] { 14 | fn len(&self) -> usize { 15 | <[T]>::len(self) 16 | } 17 | } 18 | 19 | pub trait SlicelikeMut: Slicelike + IndexMut 20 | where 21 | Self::Output: Sized, 22 | { 23 | } 24 | 25 | impl SlicelikeMut for U 26 | where 27 | U: Slicelike + IndexMut, 28 | U::Output: Sized, 29 | { 30 | } 31 | -------------------------------------------------------------------------------- /c++/stl/vector.cpp: -------------------------------------------------------------------------------- 1 | template class vector { 2 | public: 3 | int sz, max_size; 4 | T* arr; 5 | vector() { 6 | sz = 0; 7 | max_size = 4; 8 | arr = new T[max_size]; 9 | } 10 | ~vector() { delete[] arr; } 11 | void push_back(T a) { 12 | if (sz == max_size) { 13 | T* tarr = new T[max_size + max_size]; 14 | max_size += max_size; 15 | for (int i = 0; i < sz; i++) tarr[i] = arr[i]; 16 | delete[] arr; 17 | arr = tarr; 18 | } 19 | arr[sz++] = a; 20 | } 21 | void pop_back() { if (sz > 0) sz--; } 22 | int size() { return sz; } 23 | bool empty() { return sz == 0; } 24 | void clear() { sz = 0; } 25 | T &operator[](int idx) { return arr[idx]; } 26 | }; 27 | -------------------------------------------------------------------------------- /c++/stl/merge sort.cpp: -------------------------------------------------------------------------------- 1 | template 2 | bool default_compare(T a, T b) { 3 | return a < b; 4 | } 5 | 6 | template void merge_sort(T* st, T* en, bool(*cmp)(T, T) = default_compare) { 7 | int N = en - st; 8 | if (N <= 1) return; 9 | 10 | int M = N / 2; 11 | merge_sort(st, st + M, cmp); 12 | merge_sort(st + M, en, cmp); 13 | 14 | T* u = new T[N + 1]; 15 | 16 | int p1 = 0, p2 = M, p = 0; 17 | while (p1 < M && p2 < N) { 18 | if (cmp(st[p1], st[p2])) u[p++] = *(st + p1++); 19 | else u[p++] = *(st + p2++); 20 | } 21 | while (p1 < M) u[p++] = *(st + p1++); 22 | while (p2 < N) u[p++] = *(st + p2++); 23 | for (int i = 0; i < N; i++) *(st + i) = u[i]; 24 | 25 | delete[] u; 26 | return; 27 | } -------------------------------------------------------------------------------- /rust/misc/time_tracker.rs: -------------------------------------------------------------------------------- 1 | use std::time::{Duration, Instant}; 2 | 3 | pub struct TimeTracker(Instant, bool); 4 | 5 | impl TimeTracker { 6 | pub fn new() -> Self { 7 | Self(Instant::now(), true) 8 | } 9 | 10 | pub fn elapsed(&self) -> Duration { 11 | self.0.elapsed() 12 | } 13 | 14 | pub fn disable(&mut self) { 15 | self.1 = false; 16 | } 17 | 18 | pub fn milestone(&mut self, name: &str) { 19 | if self.1 { 20 | eprintln!("{}: {}ms", name, self.elapsed().as_millis()); 21 | } 22 | self.0 = Instant::now(); 23 | } 24 | } 25 | impl Default for TimeTracker { 26 | fn default() -> Self { 27 | Self::new() 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /rust/collections/slice_ext/next_permutation.rs: -------------------------------------------------------------------------------- 1 | pub trait NextPermutation { 2 | fn next_permutation(&mut self) -> bool; 3 | } 4 | 5 | impl NextPermutation for [T] { 6 | fn next_permutation(&mut self) -> bool { 7 | if self.len() <= 1 { 8 | return false; 9 | } 10 | let mut i = self.len() - 1; 11 | while i > 0 && self[i - 1] >= self[i] { 12 | i -= 1; 13 | } 14 | if i == 0 { 15 | return false; 16 | } 17 | let mut j = self.len() - 1; 18 | while self[j] <= self[i - 1] { 19 | j -= 1; 20 | } 21 | self.swap(i - 1, j); 22 | self[i..].reverse(); 23 | true 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /c++/graph/disjoint_set.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const int SZ = 10; 4 | 5 | class DisjointSet { 6 | private: 7 | int Parent[SZ]; 8 | public: 9 | void init(int n) { 10 | for (int i = 1; i <= n; i++) Parent[i] = i; 11 | } 12 | int findRoot(int x) { 13 | if (x == Parent[x]) return x; 14 | return (Parent[x] = findRoot(Parent[x])); 15 | } 16 | void Union(int x, int y) { 17 | Parent[findRoot(x)] = findRoot(y); 18 | } 19 | bool sameGroup(int x, int y) { 20 | return (findRoot(x) == findRoot(y)); 21 | } 22 | }; 23 | 24 | int main() { 25 | DisjointSet s; 26 | s.init(5); 27 | s.Union(1, 2); 28 | s.Union(4, 5); 29 | s.Union(1, 4); 30 | printf("%d\n", (int)s.sameGroup(1, 3)); 31 | printf("%d\n", (int)s.sameGroup(2, 4)); 32 | } -------------------------------------------------------------------------------- /c++/math/karatsuba.cpp: -------------------------------------------------------------------------------- 1 | typedef vector VI; 2 | VI MULTI(VI X, VI Y) { 3 | int N = X.size(), N2 = N / 2; 4 | VI R(N * 2, 0); 5 | if (N > 100) { 6 | VI X2(X.begin() + N2, X.end()); 7 | VI Y2(Y.begin() + N2, Y.end()); 8 | X.resize(N2); Y.resize(N2); 9 | 10 | VI A = MULTI(X, Y); 11 | VI B = MULTI(X2, Y2); 12 | for (int i = 0; i < N2; i++) X2[i] += X[i], Y2[i] += Y[i]; 13 | VI C = MULTI(X2, Y2); 14 | 15 | for (int i = 0; i < A.size(); i++) R[i] += A[i], C[i] -= A[i]; 16 | for (int i = 0; i < B.size(); i++) R[i + N2 * 2] += B[i], C[i] -= B[i]; 17 | for (int i = 0; i < C.size(); i++) R[i + N2] += C[i]; 18 | } 19 | else { 20 | for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) R[i + j] += X[i] * Y[j]; 21 | } 22 | return R; 23 | } -------------------------------------------------------------------------------- /c++/string/z.cpp: -------------------------------------------------------------------------------- 1 | // Z[i] : maximum common prefix length of &s[0] and &s[i] 2 | // O(|s|) 3 | using seq_t = string; 4 | vector z_func(const seq_t &s) { 5 | vector z(s.size()); 6 | z[0] = s.size(); 7 | int l = 0, r = 0; 8 | for (int i = 1; i < s.size(); i++) { 9 | if (i > r) { 10 | int j; 11 | for (j = 0; i + j < s.size() && s[i + j] == s[j]; j++) ; 12 | z[i] = j; l = i; r = i + j - 1; 13 | } else if (z[i - l] < r - i + 1) { 14 | z[i] = z[i - l]; 15 | } else { 16 | int j; 17 | for (j = 1; r + j < s.size() && s[r + j] == s[r - i + j]; j++) ; 18 | z[i] = r - i + j; l = i; r += j - 1; 19 | } 20 | } 21 | return z; 22 | } -------------------------------------------------------------------------------- /c++/data_stucture/fenwick-RangeSum.cpp: -------------------------------------------------------------------------------- 1 | typedef long long ll; 2 | 3 | const int MAXN = 1e5+5; 4 | 5 | class RangeSumBIT { 6 | public: 7 | ll BIT[2][MAXN]; 8 | //add value v to index p 9 | void Upd(int r, int p, ll v) { for (; p <= N; p+=p&(-p)) BIT[r][p]+=v; } 10 | //add value v to range [L, R] 11 | void RangeUpd(int L, int R, ll v) { 12 | Upd(0, L, v); Upd(0, R+1, -v); 13 | Upd(1, L, v*(ll)(L-1)); Upd(1, R+1, -v*(ll)(R)); 14 | } 15 | ll SumQuery(int r, int p) { 16 | ll sum = 0; 17 | for (; p > 0; p-=p&(-p)) sum += BIT[r][p]; 18 | return sum; 19 | } 20 | //return the sum of range [1, p] 21 | ll SumAll(int p) { return SumQuery(0, p)*(ll)p - SumQuery(1, p); } 22 | //return the sum of range [L, R] 23 | ll RangeSum(int L, int R) { return SumAll(R)-SumAll(L-1); } 24 | }; -------------------------------------------------------------------------------- /rust/string/string_algorithms/prefix_function.rs: -------------------------------------------------------------------------------- 1 | use crate::string::slicelike::Slicelike; 2 | 3 | pub trait PrefixFunction { 4 | fn prefix_function(&self) -> Vec; 5 | } 6 | 7 | impl PrefixFunction for S 8 | where 9 | S::Output: PartialEq + Sized, 10 | { 11 | fn prefix_function(&self) -> Vec { 12 | let mut res = Vec::with_capacity(self.len()); 13 | res.push(0); 14 | for i in 1..self.len() { 15 | let mut j = res[i - 1]; 16 | while j > 0 && self[i] != self[j] { 17 | j = res[j - 1]; 18 | } 19 | if self[i] == self[j] { 20 | j += 1; 21 | } 22 | res.push(j); 23 | } 24 | res 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /rust/graph/edges/edge_id.rs: -------------------------------------------------------------------------------- 1 | pub trait EdgeId: Clone { 2 | fn new() -> Self; 3 | fn id(&self) -> usize; 4 | fn set_id(&mut self, id: usize); 5 | } 6 | 7 | #[derive(Clone)] 8 | pub struct WithId { 9 | id: u32, 10 | } 11 | 12 | impl EdgeId for WithId { 13 | fn new() -> Self { 14 | Self { id: 0 } 15 | } 16 | 17 | fn id(&self) -> usize { 18 | self.id as usize 19 | } 20 | 21 | fn set_id(&mut self, id: usize) { 22 | self.id = id as u32; 23 | } 24 | } 25 | 26 | #[derive(Clone)] 27 | pub struct NoId {} 28 | 29 | impl EdgeId for NoId { 30 | fn new() -> Self { 31 | Self {} 32 | } 33 | 34 | fn id(&self) -> usize { 35 | panic!("Id called on no id") 36 | } 37 | 38 | fn set_id(&mut self, _: usize) {} 39 | } 40 | -------------------------------------------------------------------------------- /c++/settings/sublime.cpp: -------------------------------------------------------------------------------- 1 | 1. Preferences - Settings 2 | { 3 | "color_scheme": "Packages/Color Scheme - Default/Monokai.tmTheme", 4 | "font_face": "Ubuntu Mono Regular", 5 | "font_size": 15, 6 | "ignored_packages": ["Vintage"], 7 | "theme": "Default.sublime-theme" 8 | } 9 | 2. Preferences - Key Bindings 10 | [ 11 | { "keys": ["ctrl+shift+i"], "command": "reindent" , "args": { "single_line": false } } 12 | ] 13 | 3. Tools - Build System - New Build System 14 | { 15 | "shell_cmd": "g++ \"${file}\" -o \"${file_path}/${file_base_name}\"", 16 | "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", 17 | "working_dir": "${file_path}", 18 | "selector": "source.c, source.c++", 19 | "variants": 20 | [ 21 | { 22 | "name": "Run", 23 | "shell_cmd": "g++ -std=c++11 \"${file}\" -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\" < input.txt" 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /rust/collections/test.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::iter_ext::find_count::IterFindCount; 2 | use crate::collections::permutation::Permutation; 3 | use crate::collections::slice_ext::compress::compress; 4 | 5 | #[test] 6 | fn test_find() { 7 | let v = vec![1, 2, 3]; 8 | assert_eq!(Some(1), v.iter().find(&2)); 9 | assert_eq!(None, v.iter().find(&0)); 10 | } 11 | 12 | #[test] 13 | fn test_permutation_mul() { 14 | let p = Permutation::new_with_base(vec![1, 3, 2], 1); 15 | let q = Permutation::new_with_base(vec![2, 1, 3], 1); 16 | assert_eq!(&p * &q, Permutation::new(vec![2, 0, 1])); 17 | assert_eq!(&q * &p, Permutation::new(vec![1, 2, 0])); 18 | } 19 | 20 | #[test] 21 | fn test_compress() { 22 | let a = vec![3, 5, 7]; 23 | let b = vec![7, 4, 5]; 24 | assert_eq!( 25 | compress([&a, &b]), 26 | (vec![3, 4, 5, 7], [vec![0, 2, 3], vec![3, 1, 2]]) 27 | ); 28 | } 29 | -------------------------------------------------------------------------------- /c++/math/point_in_poly.cpp: -------------------------------------------------------------------------------- 1 | typedef double coord_t; 2 | inline coord_t is_left(Point p0, Point p1, Point p2) { 3 | return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y); 4 | } 5 | // point in polygon test 6 | // http://geomalgorithms.com/a03-_inclusion.html 7 | bool is_in_polygon(Point p, vector& poly) { 8 | int wn = 0; 9 | for (int i = 0; i < poly.size(); ++i) { 10 | int ni = (i + 1 == poly.size()) ? 0 : i + 1; 11 | if (poly[i].y <= p.y) { 12 | if (poly[ni].y > p.y) { 13 | if (is_left(poly[i], poly[ni], p) > 0) { 14 | ++wn; 15 | } 16 | } 17 | } 18 | else { 19 | if (poly[ni].y <= p.y) { 20 | if (is_left(poly[i], poly[ni], p) < 0) { 21 | --wn; 22 | } 23 | } 24 | } 25 | } 26 | return wn != 0; 27 | } -------------------------------------------------------------------------------- /rust/collections/iter_ext/min_max.rs: -------------------------------------------------------------------------------- 1 | pub trait IterMinMaxPos: Iterator + Sized { 2 | fn max_position(self) -> Option { 3 | let mut res = None; 4 | let mut val: Option = None; 5 | for (i, cur) in self.enumerate() { 6 | if val.is_none() || *val.as_ref().unwrap() < cur { 7 | val = Some(cur); 8 | res = Some(i); 9 | } 10 | } 11 | res 12 | } 13 | 14 | fn min_position(self) -> Option { 15 | let mut res = None; 16 | let mut val = None; 17 | for (i, cur) in self.enumerate() { 18 | if val.is_none() || *val.as_ref().unwrap() > cur { 19 | val = Some(cur); 20 | res = Some(i); 21 | } 22 | } 23 | res 24 | } 25 | } 26 | 27 | impl + Sized> IterMinMaxPos for I {} 28 | -------------------------------------------------------------------------------- /rust/io/input_iter.rs: -------------------------------------------------------------------------------- 1 | use crate::io::input::{Input, Readable}; 2 | use std::marker::PhantomData; 3 | 4 | pub struct InputIterator<'t, 's: 't, T: Readable + 't + 's> { 5 | input: &'t mut Input<'s>, 6 | phantom: PhantomData, 7 | } 8 | 9 | impl<'t, 's: 't, T: Readable + 't + 's> Iterator for InputIterator<'t, 's, T> { 10 | type Item = T; 11 | 12 | fn next(&mut self) -> Option { 13 | self.input.skip_whitespace(); 14 | self.input.peek().map(|_| self.input.read()) 15 | } 16 | } 17 | 18 | pub trait InputIterable<'t, 's: 't> { 19 | fn iter(&'t mut self) -> InputIterator<'t, 's, T>; 20 | } 21 | 22 | impl<'t, 's: 't> InputIterable<'t, 's> for Input<'s> { 23 | fn iter(&'t mut self) -> InputIterator<'t, 's, T> { 24 | InputIterator { 25 | input: self, 26 | phantom: PhantomData, 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /rust/graph/flow_graph.rs: -------------------------------------------------------------------------------- 1 | use crate::graph::edges::flow_edge_trait::FlowEdgeTrait; 2 | use crate::graph::graph::Graph; 3 | use crate::numbers::num_traits::add_sub::AddSub; 4 | use crate::numbers::num_traits::zero_one::ZeroOne; 5 | 6 | pub trait FlowGraph> { 7 | fn push_flow(&mut self, push_data: (usize, usize, C)); 8 | } 9 | 10 | impl> FlowGraph for Graph { 11 | fn push_flow(&mut self, (to, reverse_id, flow): (usize, usize, C)) { 12 | *self.edges[to][reverse_id].capacity_mut() += flow; 13 | let from = self.edges[to][reverse_id].to(); 14 | let direct_id = self.edges[to][reverse_id].reverse_id(); 15 | let direct = &mut self.edges[from][direct_id]; 16 | assert!(flow >= C::zero() && flow <= direct.capacity()); 17 | *direct.capacity_mut() -= flow; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /rust/numbers/integer_sqrt.rs: -------------------------------------------------------------------------------- 1 | pub trait IntegerSqrt: Sized { 2 | fn sqrt(self) -> Option; 3 | fn lower_sqrt(self) -> Self; 4 | fn upper_sqrt(self) -> Self; 5 | } 6 | 7 | impl IntegerSqrt for i64 { 8 | fn sqrt(self) -> Option { 9 | let s = self.lower_sqrt(); 10 | if s * s == self { 11 | Some(s) 12 | } else { 13 | None 14 | } 15 | } 16 | 17 | fn lower_sqrt(self) -> Self { 18 | assert!(self >= 0); 19 | let mut s = (self as f64).sqrt().round() as i64; 20 | while s * s > self { 21 | s -= 1; 22 | } 23 | while (s + 1) * (s + 1) <= self { 24 | s += 1; 25 | } 26 | s 27 | } 28 | 29 | fn upper_sqrt(self) -> Self { 30 | let s = self.lower_sqrt(); 31 | if s * s == self { 32 | s 33 | } else { 34 | s + 1 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /rust/collections/slice_ext/compress.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::slice_ext::bounds::Bounds; 2 | use std::mem::MaybeUninit; 3 | 4 | pub fn compress(vs: [&[T]; N]) -> (Vec, [Vec; N]) { 5 | let mut size = 0; 6 | for v in &vs { 7 | size += v.len(); 8 | } 9 | let mut all = Vec::with_capacity(size); 10 | for v in &vs { 11 | all.extend_from_slice(v); 12 | } 13 | all.sort(); 14 | all.dedup(); 15 | let arrs = unsafe { 16 | let mut arr: MaybeUninit<[Vec; N]> = MaybeUninit::uninit(); 17 | for (i, v) in vs.iter().enumerate() { 18 | let mut cur = Vec::with_capacity(vs[i].len()); 19 | for vv in *v { 20 | cur.push(all.bin_search(vv).unwrap()); 21 | } 22 | arr.as_mut_ptr().cast::>().add(i).write(cur); 23 | } 24 | arr.assume_init() 25 | }; 26 | (all, arrs) 27 | } 28 | -------------------------------------------------------------------------------- /rust/geometry/angle.rs: -------------------------------------------------------------------------------- 1 | use crate::geometry::geometry_utils::canonize_angle_base; 2 | use crate::geometry::point::Point; 3 | use crate::geometry::ray::Ray; 4 | use crate::numbers::num_traits::real::RealTrait; 5 | 6 | pub struct Angle { 7 | pub origin: Point, 8 | pub dir1: Point, 9 | pub dir2: Point, 10 | } 11 | 12 | impl Angle { 13 | pub fn new(origin: Point, dir1: Point, dir2: Point) -> Self { 14 | Self { origin, dir1, dir2 } 15 | } 16 | } 17 | 18 | impl Angle { 19 | pub fn value(&self) -> T { 20 | let a1 = (self.dir1 - self.origin).angle(); 21 | let a2 = (self.dir2 - self.origin).angle(); 22 | canonize_angle_base(a2 - a1, T::zero()) 23 | } 24 | 25 | pub fn bissector(&self) -> Ray { 26 | let angle = (self.dir1 - self.origin).angle(); 27 | Ray::from_angle(self.origin, angle + self.value() / (T::one() + T::one())) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /rust/misc/memo/test.rs: -------------------------------------------------------------------------------- 1 | mod memoization_test { 2 | use crate::misc::memo::memoization::Memoization2; 3 | use crate::misc::memo::memoization_2d::Memoization2d; 4 | use crate::misc::recursive_function::Callable2; 5 | use crate::numbers::mod_int::ModIntF; 6 | use crate::numbers::num_traits::zero_one::ZeroOne; 7 | 8 | #[test] 9 | fn test() { 10 | type Mod = ModIntF; 11 | let mut mem2d = Memoization2d::new(1001, 1001, |f, n, m| { 12 | if n == 0 || m == 0 { 13 | Mod::one() 14 | } else { 15 | f.call(n - 1, m) + f.call(n, m - 1) 16 | } 17 | }); 18 | let mut mem = Memoization2::new(|f, n, m| { 19 | if n == 0 || m == 0 { 20 | Mod::one() 21 | } else { 22 | f.call(n - 1, m) + f.call(n, m - 1) 23 | } 24 | }); 25 | assert_eq!(mem.call(1000, 1000), mem2d.call(1000, 1000)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /rust/numbers/num_traits/ord.rs: -------------------------------------------------------------------------------- 1 | pub trait MinMax: PartialOrd { 2 | fn min_val() -> Self; 3 | fn max_val() -> Self; 4 | #[must_use] 5 | fn minimum(self, other: Self) -> Self; 6 | #[must_use] 7 | fn maximum(self, other: Self) -> Self; 8 | } 9 | 10 | macro_rules! min_max_integer_impl { 11 | ($($t: ident)+) => {$( 12 | impl MinMax for $t { 13 | fn min_val() -> Self { 14 | // 1.43 15 | std::$t::MIN 16 | } 17 | 18 | fn max_val() -> Self { 19 | // 1.43 20 | std::$t::MAX 21 | } 22 | 23 | fn minimum(self, other: Self) -> Self { 24 | Self::min(self, other) 25 | } 26 | 27 | fn maximum(self, other: Self) -> Self { 28 | Self::max(self, other) 29 | } 30 | } 31 | )+}; 32 | } 33 | 34 | min_max_integer_impl!(i128 i64 i32 i16 i8 isize u128 u64 u32 u16 u8 usize); 35 | -------------------------------------------------------------------------------- /rust/string/string_algorithms/z_algorithm.rs: -------------------------------------------------------------------------------- 1 | use crate::string::slicelike::Slicelike; 2 | 3 | pub trait ZAlgorithm { 4 | fn z_algorithm(&self) -> Vec; 5 | } 6 | 7 | impl ZAlgorithm for S 8 | where 9 | S::Output: PartialEq + Sized, 10 | { 11 | fn z_algorithm(&self) -> Vec { 12 | let mut res = Vec::with_capacity(self.len()); 13 | res.push(0); 14 | let mut l = 0; 15 | let mut r = 0; 16 | for i in 1..self.len() { 17 | if i <= r { 18 | let cur = (r - i + 1).min(res[i - l]); 19 | res.push(cur); 20 | } else { 21 | res.push(0); 22 | } 23 | while i + res[i] < self.len() && self[res[i]] == self[i + res[i]] { 24 | res[i] += 1; 25 | } 26 | if i + res[i] - 1 > r { 27 | l = i; 28 | r = i + res[i] - 1; 29 | } 30 | } 31 | res 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /rust/numbers/num_traits/sign.rs: -------------------------------------------------------------------------------- 1 | pub trait IsSigned { 2 | const SIGNED: bool; 3 | } 4 | 5 | pub trait Signed: IsSigned {} 6 | 7 | pub trait Unsigned: IsSigned { 8 | fn distance(self, other: Self) -> Self; 9 | } 10 | 11 | macro_rules! unsigned_impl { 12 | ($($t: ident)+) => {$( 13 | impl Unsigned for $t { 14 | fn distance(self, other: Self) -> Self { 15 | if self > other { 16 | self - other 17 | } else { 18 | other - self 19 | } 20 | } 21 | } 22 | 23 | impl IsSigned for $t { 24 | const SIGNED: bool = false; 25 | } 26 | )+}; 27 | } 28 | 29 | unsigned_impl!(u128 u64 u32 u16 u8 usize); 30 | 31 | macro_rules! signed_impl { 32 | ($($t: ident)+) => {$( 33 | impl Signed for $t {} 34 | 35 | impl IsSigned for $t { 36 | const SIGNED: bool = true; 37 | } 38 | )+}; 39 | } 40 | 41 | signed_impl!(i128 i64 i32 i16 i8 isize); 42 | -------------------------------------------------------------------------------- /rust/numbers/gcd.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::num_traits::add_sub::AddSub; 2 | use crate::numbers::num_traits::mul_div_rem::{MulDivRem, Multable}; 3 | use crate::numbers::num_traits::wideable::Wideable; 4 | use crate::numbers::num_traits::zero_one::ZeroOne; 5 | use std::mem::swap; 6 | 7 | pub fn extended_gcd( 8 | a: T, 9 | b: T, 10 | ) -> (T, T::W, T::W) 11 | where 12 | T::W: Copy + ZeroOne + AddSub + Multable, 13 | { 14 | if a == T::zero() { 15 | (b, T::W::zero(), T::W::one()) 16 | } else { 17 | let (d, y, mut x) = extended_gcd(b % a, a); 18 | x -= T::W::from(b / a) * y; 19 | (d, x, y) 20 | } 21 | } 22 | 23 | pub fn gcd(mut a: T, mut b: T) -> T { 24 | while b != T::zero() { 25 | a %= b; 26 | swap(&mut a, &mut b); 27 | } 28 | a 29 | } 30 | 31 | pub fn lcm(a: T, b: T) -> T { 32 | (a / gcd(a, b)) * b 33 | } 34 | -------------------------------------------------------------------------------- /c++/string/manacher.cpp: -------------------------------------------------------------------------------- 1 | const char DUMMY = '.'; 2 | 3 | int manacher(string s) { 4 | // Add dummy character to not consider odd/even length 5 | // NOTE: Ensure DUMMY does not appear in input 6 | // NOTE: Remember to ignore DUMMY when tracing 7 | 8 | int n = s.size() * 2 - 1; 9 | vector f = vector (n, 0); 10 | string a = string(n, DUMMY); 11 | for (int i = 0; i < n; i += 2) a[i] = s[i / 2]; 12 | 13 | int l = 0, r = -1, center, res = 0; 14 | for (int i = 0, j = 0; i < n; i++) { 15 | j = (i > r ? 0 : min(f[l + r - i], r - i)) + 1; 16 | while (i - j >= 0 && i + j < n && a[i - j] == a[i + j]) j++; 17 | f[i] = --j; 18 | if (i + j > r) { 19 | r = i + j; 20 | l = i - j; 21 | } 22 | 23 | int len = (f[i] + i % 2) / 2 * 2 + 1 - i % 2; 24 | if (len > res) { 25 | res = len; 26 | center = i; 27 | } 28 | } 29 | // a[center - f[center]..center + f[center]] is the needed substring 30 | return res; 31 | } -------------------------------------------------------------------------------- /rust/collections/iter_ext/interleave.rs: -------------------------------------------------------------------------------- 1 | enum NextFrom { 2 | First, 3 | Second, 4 | } 5 | 6 | pub struct Interleave, J: Iterator> { 7 | iter1: I, 8 | iter2: J, 9 | next_from: NextFrom, 10 | } 11 | 12 | impl, J: Iterator> Iterator for Interleave { 13 | type Item = T; 14 | 15 | fn next(&mut self) -> Option { 16 | match self.next_from { 17 | NextFrom::First => { 18 | self.next_from = NextFrom::Second; 19 | self.iter1.next() 20 | } 21 | NextFrom::Second => { 22 | self.next_from = NextFrom::First; 23 | self.iter2.next() 24 | } 25 | } 26 | } 27 | } 28 | 29 | pub fn interleave, J: Iterator>( 30 | iter1: I, 31 | iter2: J, 32 | ) -> Interleave { 33 | Interleave { 34 | iter1, 35 | iter2, 36 | next_from: NextFrom::First, 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /python/Math/64bit-fftmod.py: -------------------------------------------------------------------------------- 1 | from random import * 2 | import time 3 | 4 | def ilog2(n): 5 | return 0 if n <= 0 else n.bit_length() - 1 6 | 7 | def pack(pack, shamt): 8 | size = len(pack) 9 | while size > 1: 10 | npack = [] 11 | for i in range(0, size - 1, 2): 12 | npack += [pack[i] | (pack[i+1] << shamt)] 13 | if size & 1: 14 | npack += [pack[-1]] 15 | pack, size, shamt = npack, (size + 1) >> 1, shamt << 1 16 | return pack[0] 17 | 18 | def unpack(M, size, shamt): 19 | s, sizes = size, [] 20 | while s > 1: 21 | sizes += [s] 22 | s = (s + 1) >> 1 23 | ret = [M] 24 | for size in sizes[::-1]: 25 | mask, nret = (1 << shamt) - 1, [] 26 | for c in ret: 27 | nret += [c & mask, c >> shamt] 28 | ret, shamt = nret[:size], shamt >> 1 29 | return ret 30 | 31 | def poly_mul(f, g, mod = 1000000007): 32 | size = min(len(f), len(g)) 33 | shift = ((mod - 1) ** 2 * size).bit_length() 34 | rsize = len(f) + len(g) - 1 35 | h = unpack(pack(f, shift) * pack(g, shift), rsize, shift * (1 << ilog2(rsize - 1))) 36 | return [int(x % mod) for x in h] -------------------------------------------------------------------------------- /c++/math/faulhaber's_formula.cpp: -------------------------------------------------------------------------------- 1 | /* 1^K + 2^K + ... + N^K */ 2 | /* O(K^2) */ 3 | long long mod = 1000000007; 4 | long long s[55], N, c[55][55], d[55][55]; 5 | int K; 6 | long long f(long long a, long long b) { 7 | if (b == 0) return 1; 8 | if (b == 1) return a % mod; 9 | long long v = f(a, b / 2); 10 | if (b & 1) return (((a*v) % mod)*v) % mod; 11 | return (v*v) % mod; 12 | } 13 | int main() { 14 | c[0][0] = c[1][0] = c[1][1] = 1; 15 | scanf("%lld%d", &N, &K); 16 | for (int i = 2; i <= K + 1; i++) { 17 | c[i][0] = 1; 18 | for (int j = 1; j <= i; j++) c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod; 19 | } 20 | s[0] = N%mod; 21 | for (int j = 1; j <= K + 1; j++) d[0][j] = (s[0] * c[j][0]) % mod; 22 | for (int k = 1; k <= K; k++) { 23 | long long a = (N + 1); 24 | for (int j = 2; j <= k + 1; j++) a = (a*(N + 1)) % mod; 25 | a--; 26 | if (a < 0) a += mod; 27 | for (int j = 0; j < k; j++) a = (a - d[j][k + 1] + mod) % mod; 28 | s[k] = (a * f(c[k + 1][k], mod - 2)) % mod; 29 | for (int j = k; j <= K + 1; j++) d[k][j] = (s[k] * c[j][k]) % mod; 30 | } 31 | printf("%lld", s[K]); 32 | } -------------------------------------------------------------------------------- /rust/numbers/fwht.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::num_traits::add_sub::AddSub; 2 | use crate::numbers::num_traits::as_index::AsIndex; 3 | use crate::numbers::num_traits::mul_div_rem::MulDiv; 4 | 5 | pub trait FWHT { 6 | fn fwht(&mut self, inverse: bool); 7 | } 8 | 9 | impl FWHT for [T] { 10 | fn fwht(&mut self, inverse: bool) { 11 | assert!(!self.is_empty()); 12 | let n = self.len(); 13 | assert_eq!(n & (n - 1), 0); 14 | let mut len = 1; 15 | while len < n { 16 | for i in (0..n).step_by(2 * len) { 17 | let (head, tail) = self.split_at_mut(i + len); 18 | for (u, v) in head.iter_mut().skip(i).zip(tail.iter_mut().take(len)) { 19 | let nu = *u + *v; 20 | *v = *u - *v; 21 | *u = nu; 22 | } 23 | } 24 | len *= 2; 25 | } 26 | 27 | if inverse { 28 | for p in self.iter_mut() { 29 | *p /= T::from_index(n); 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /c++/graph/Flow with Demands.cpp: -------------------------------------------------------------------------------- 1 | struct MaxFlowEdgeDemands 2 | { 3 | MaxFlowDinic mf; 4 | using flow_t = MaxFlowDinic::flow_t; 5 | 6 | vector ind, outd; 7 | flow_t D; int n; 8 | 9 | void init(int _n) { 10 | n = _n; D = 0; mf.init(n + 2); 11 | ind.clear(); outd.clear(); 12 | ind.resize(n, 0); outd.resize(n, 0); 13 | } 14 | 15 | void add_edge(int s, int e, flow_t cap, flow_t demands = 0) { 16 | mf.add_edge(s, e, cap - demands); 17 | D += demands; ind[e] += demands; outd[s] += demands; 18 | } 19 | 20 | // returns { false, 0 } if infeasible 21 | // { true, maxflow } if feasible 22 | pair solve(int source, int sink) { 23 | mf.add_edge(sink, source, numeric_limits::max()); 24 | 25 | for (int i = 0; i < n; i++) { 26 | if (ind[i]) mf.add_edge(n, i, ind[i]); 27 | if (outd[i]) mf.add_edge(i, n + 1, outd[i]); 28 | } 29 | 30 | if (mf.solve(n, n + 1) != D) return{ false, 0 }; 31 | 32 | for (int i = 0; i < n; i++) { 33 | if (ind[i]) mf.graph[i].pop_back(); 34 | if (outd[i]) mf.graph[i].pop_back(); 35 | } 36 | 37 | return{ true, mf.solve(source, sink) }; 38 | } 39 | }; -------------------------------------------------------------------------------- /rust/misc/memo/memoization_vec.rs: -------------------------------------------------------------------------------- 1 | use crate::misc::recursive_function::Callable; 2 | 3 | pub struct Memoization1d 4 | where 5 | F: FnMut(&mut dyn Callable, usize) -> Output, 6 | { 7 | f: std::cell::UnsafeCell, 8 | res: Vec>, 9 | } 10 | 11 | impl Memoization1d 12 | where 13 | F: FnMut(&mut dyn Callable, usize) -> Output, 14 | { 15 | pub fn new(len: usize, f: F) -> Self { 16 | Self { 17 | f: std::cell::UnsafeCell::new(f), 18 | res: vec![None; len], 19 | } 20 | } 21 | } 22 | 23 | impl Callable for Memoization1d 24 | where 25 | F: FnMut(&mut dyn Callable, usize) -> Output, 26 | { 27 | fn call(&mut self, n: usize) -> Output { 28 | match self.res[n].as_ref() { 29 | None => { 30 | let res = unsafe { (*self.f.get())(self, n) }; 31 | self.res[n] = Some(res.clone()); 32 | res 33 | } 34 | Some(res) => res.clone(), 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Hongjun Jang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /c++/graph/scc.cpp: -------------------------------------------------------------------------------- 1 | const int MAXN = 100; 2 | vector graph[MAXN]; 3 | int up[MAXN], visit[MAXN], vtime; 4 | vector stk; 5 | int scc_idx[MAXN], scc_cnt; 6 | 7 | void dfs(int nod) { 8 | up[nod] = visit[nod] = ++vtime; 9 | stk.push_back(nod); 10 | for (int next : graph[nod]) { 11 | if (visit[next] == 0) { 12 | dfs(next); 13 | up[nod] = min(up[nod], up[next]); 14 | } 15 | else if (scc_idx[next] == 0) 16 | up[nod] = min(up[nod], visit[next]); 17 | } 18 | if (up[nod] == visit[nod]) { 19 | ++scc_cnt; 20 | int t; 21 | do { 22 | t = stk.back(); 23 | stk.pop_back(); 24 | scc_idx[t] = scc_cnt; 25 | } while (!stk.empty() && t != nod); 26 | } 27 | } 28 | 29 | // find SCCs in given directed graph 30 | // O(V+E) 31 | // the order of scc_idx constitutes a reverse topological sort 32 | void get_scc() { 33 | vtime = 0; 34 | memset(visit, 0, sizeof(visit)); 35 | scc_cnt = 0; 36 | memset(scc_idx, 0, sizeof(scc_idx)); 37 | for (int i = 0; i < n; ++i) 38 | if (visit[i] == 0) dfs(i); 39 | } -------------------------------------------------------------------------------- /rust/collections/slice_ext/reversed.rs: -------------------------------------------------------------------------------- 1 | use std::ops::{Index, IndexMut}; 2 | 3 | pub struct Reversed<'a, T>(&'a [T]); 4 | 5 | impl Index for Reversed<'_, T> { 6 | type Output = T; 7 | 8 | fn index(&self, index: usize) -> &Self::Output { 9 | self.0.index(self.0.len() - index - 1) 10 | } 11 | } 12 | 13 | pub struct ReversedMut<'a, T>(&'a mut [T]); 14 | 15 | impl Index for ReversedMut<'_, T> { 16 | type Output = T; 17 | 18 | fn index(&self, index: usize) -> &Self::Output { 19 | self.0.index(self.0.len() - index - 1) 20 | } 21 | } 22 | 23 | impl IndexMut for ReversedMut<'_, T> { 24 | fn index_mut(&mut self, index: usize) -> &mut Self::Output { 25 | self.0.index_mut(self.0.len() - index - 1) 26 | } 27 | } 28 | 29 | pub trait ReversedSlice { 30 | fn rev(&self) -> Reversed; 31 | fn rev_mut(&mut self) -> ReversedMut; 32 | } 33 | 34 | impl ReversedSlice for [T] { 35 | fn rev(&self) -> Reversed { 36 | Reversed(self) 37 | } 38 | 39 | fn rev_mut(&mut self) -> ReversedMut { 40 | ReversedMut(self) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /c++/dp_opt/cht.cpp: -------------------------------------------------------------------------------- 1 | typedef long long ll; 2 | struct CHTLinear { 3 | struct Line { 4 | ll a, b; 5 | ll y(ll x) const { return a * x + b; } 6 | }; 7 | vector stk; 8 | int qpt; 9 | CHTLinear() : qpt(0) { } 10 | // when you need maximum : (previous l).a < (now l).a 11 | // when you need minimum : (previous l).a > (now l).a 12 | void add(const Line &l) { 13 | while (stk.size() > 1) { 14 | Line& l0 = stk[stk.size() - 1]; 15 | Line& l1 = stk[stk.size() - 2]; 16 | if ((l0.b - l.b) * (l0.a - l1.a) > (l1.b - l0.b) * (l.a - l0.a)) break; 17 | stk.pop_back(); 18 | } 19 | stk.push_back(l); 20 | } 21 | // (previous x) <= (current x) 22 | // it calculates max/min at x 23 | ll query(ll x) { 24 | while (qpt + 1 < stk.size()) { 25 | Line& l0 = stk[qpt]; 26 | Line& l1 = stk[qpt + 1]; 27 | if (l1.a - l0.a > 0 && (l0.b - l1.b) > x * (l1.a - l0.a)) break; 28 | if (l1.a - l0.a < 0 && (l0.b - l1.b) < x * (l1.a - l0.a)) break; 29 | ++qpt; 30 | } 31 | return stk[qpt].y(x); 32 | } 33 | }; -------------------------------------------------------------------------------- /rust/collections/iter_ext/cur_next.rs: -------------------------------------------------------------------------------- 1 | use crate::zip; 2 | use std::iter::once; 3 | 4 | pub fn cur_next(n: usize) -> impl Iterator { 5 | (0..n).zip((1..n).chain(once(0))) 6 | } 7 | 8 | pub fn prev_cur_next(n: usize) -> impl Iterator { 9 | zip!(once(n - 1).chain(0..n - 1), 0..n, (1..n).chain(once(0))) 10 | } 11 | 12 | #[macro_export] 13 | macro_rules! zip { 14 | ( @closure $p:pat => $tup:expr ) => { 15 | |$p| $tup 16 | }; 17 | 18 | ( @closure $p:pat => ( $($tup:tt)* ) , $_iter:expr $( , $tail:expr )* ) => { 19 | zip!(@closure ($p, b) => ( $($tup)*, b ) $( , $tail )*) 20 | }; 21 | 22 | ($first:expr $(,)*) => { 23 | std::iter::IntoIterator::into_iter($first) 24 | }; 25 | 26 | // binary 27 | ($first:expr, $second:expr $(,)*) => { 28 | zip!($first).zip($second) 29 | }; 30 | 31 | // n-ary where n > 2 32 | ( $first:expr $( , $rest:expr )* $(,)* ) => { 33 | zip!($first) 34 | $( 35 | .zip($rest) 36 | )* 37 | .map( 38 | zip!(@closure a => (a) $( , $rest )*) 39 | ) 40 | }; 41 | } 42 | -------------------------------------------------------------------------------- /c++/graph/Centroid Decomposition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int MAXN = 100005; 5 | 6 | int N; 7 | int vis[MAXN], sub[MAXN], maxsub[MAXN]; 8 | vector g[MAXN], dfn; 9 | 10 | void dfs(int x, int par) { 11 | dfn.push_back(x); 12 | sub[x] = 1; maxsub[x] = 0; 13 | for (auto &y : g[x]) { 14 | if (vis[y] || y == par) continue; 15 | dfs(y, x); 16 | maxsub[x] = max(maxsub[x], sub[y]); 17 | sub[x] += sub[y]; 18 | } 19 | } 20 | 21 | int centroid(int x) { 22 | dfn.clear(); 23 | dfs(x, -1); 24 | int dfns = dfn.size(); 25 | int maxs = 1e9, center = -1; 26 | for (auto &t : dfn) { 27 | int sz = max(maxsub[t], dfns - sub[t]); 28 | if (maxs > sz) { 29 | maxs = sz; 30 | center = t; 31 | } 32 | } 33 | return center; 34 | } 35 | 36 | int main() { 37 | scanf("%d", &N); 38 | for (int i = 1; i < N; i++) { 39 | int x, y; scanf("%d%d", &x, &y); 40 | g[x].push_back(y); 41 | g[y].push_back(x); 42 | } 43 | queue qu; qu.push(1); 44 | while (!qu.empty()) { 45 | int x = qu.front(); qu.pop(); 46 | x = centroid(x); 47 | //printf("%d\n", x); 48 | vis[x] = 1; 49 | for (auto &y : g[x]) if (!vis[y]) { 50 | qu.push(y); 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /rust/graph/minimal_spanning_tree.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::dsu::DSU; 2 | use crate::graph::edges::edge_trait::BidirectionalEdgeTrait; 3 | use crate::graph::edges::weighted_edge_trait::WeightedEdgeTrait; 4 | use crate::graph::graph::Graph; 5 | 6 | pub trait MinimalSpanningTree> { 7 | fn minimal_spanning_tree(&self) -> Graph; 8 | } 9 | 10 | impl + BidirectionalEdgeTrait> MinimalSpanningTree 11 | for Graph 12 | { 13 | fn minimal_spanning_tree(&self) -> Graph { 14 | let mut edges = Vec::with_capacity(self.edge_count()); 15 | for i in 0..self.vertex_count() { 16 | for e in &self[i] { 17 | if e.to() > i { 18 | edges.push((i, e.clone())); 19 | } 20 | } 21 | } 22 | edges.sort_by_key(|(_, e)| e.weight()); 23 | let mut res = Graph::new(self.vertex_count()); 24 | let mut dsu = DSU::new(self.vertex_count()); 25 | for (i, e) in edges { 26 | if dsu.join(i, e.to()) { 27 | res.add_edge(i, e); 28 | } 29 | } 30 | res 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /rust/string/composite_slicelike.rs: -------------------------------------------------------------------------------- 1 | use crate::string::slicelike::Slicelike; 2 | use std::ops::Index; 3 | 4 | pub struct CompositeSlicelike< 5 | 'a, 6 | T, 7 | S1: Slicelike + ?Sized, 8 | S2: Slicelike + ?Sized, 9 | > { 10 | s1: &'a S1, 11 | s2: &'a S2, 12 | phantom: std::marker::PhantomData, 13 | } 14 | 15 | pub trait SlicelikeZip: Slicelike 16 | where 17 | Self::Output: Sized, 18 | { 19 | fn zip<'a, S2: Slicelike>( 20 | &'a self, 21 | s2: &'a S2, 22 | ) -> CompositeSlicelike<'a, Self::Output, Self, S2> { 23 | CompositeSlicelike { 24 | s1: self, 25 | s2, 26 | phantom: std::marker::PhantomData, 27 | } 28 | } 29 | } 30 | 31 | impl SlicelikeZip for S where S::Output: Sized {} 32 | 33 | impl<'a, T, S1: Slicelike, S2: Slicelike> Index 34 | for CompositeSlicelike<'a, T, S1, S2> 35 | { 36 | type Output = T; 37 | 38 | fn index(&self, index: usize) -> &Self::Output { 39 | if index < self.s1.len() { 40 | &self.s1[index] 41 | } else { 42 | &self.s2[index - self.s1.len()] 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /rust/collections/min_max.rs: -------------------------------------------------------------------------------- 1 | pub trait MinimMaxim: PartialOrd + Sized { 2 | fn minim(&mut self, other: Rhs) -> bool; 3 | 4 | fn maxim(&mut self, other: Rhs) -> bool; 5 | } 6 | 7 | impl MinimMaxim for T { 8 | fn minim(&mut self, other: Self) -> bool { 9 | if other < *self { 10 | *self = other; 11 | true 12 | } else { 13 | false 14 | } 15 | } 16 | 17 | fn maxim(&mut self, other: Self) -> bool { 18 | if other > *self { 19 | *self = other; 20 | true 21 | } else { 22 | false 23 | } 24 | } 25 | } 26 | 27 | impl MinimMaxim for Option { 28 | fn minim(&mut self, other: T) -> bool { 29 | match self { 30 | None => { 31 | *self = Some(other); 32 | true 33 | } 34 | Some(v) => v.minim(other), 35 | } 36 | } 37 | 38 | fn maxim(&mut self, other: T) -> bool { 39 | match self { 40 | None => { 41 | *self = Some(other); 42 | true 43 | } 44 | Some(v) => v.maxim(other), 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /rust/numbers/primes/sieve.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::bit_set::BitSet; 2 | use crate::collections::iter_ext::collect::IterCollect; 3 | use crate::numbers::num_traits::as_index::AsIndex; 4 | 5 | pub fn primality_table(n: usize) -> BitSet { 6 | let mut res = BitSet::new(n); 7 | res.fill(true); 8 | if n > 0 { 9 | res.unset(0); 10 | } 11 | if n > 1 { 12 | res.unset(1); 13 | } 14 | let mut i = 2; 15 | while i * i < n { 16 | if res[i] { 17 | for j in ((i * i)..n).step_by(i) { 18 | res.unset(j); 19 | } 20 | } 21 | i += 1; 22 | } 23 | res 24 | } 25 | 26 | pub fn primes(n: usize) -> Vec { 27 | primality_table(n) 28 | .into_iter() 29 | .map(|i| T::from_index(i)) 30 | .collect_vec() 31 | } 32 | 33 | pub fn divisor_table(n: usize) -> Vec { 34 | let mut res = (0..n).map(|i| T::from_index(i)).collect_vec(); 35 | let mut i = 2; 36 | while i * i < n { 37 | if res[i] == T::from_index(i) { 38 | for j in ((i * i)..n).step_by(i) { 39 | res[j] = T::from_index(i); 40 | } 41 | } 42 | i += 1; 43 | } 44 | res 45 | } 46 | -------------------------------------------------------------------------------- /rust/misc/memo/memoization_2d.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::md_arr::arr2d::Arr2d; 2 | use crate::misc::recursive_function::Callable2; 3 | 4 | pub struct Memoization2d 5 | where 6 | F: FnMut(&mut dyn Callable2, usize, usize) -> Output, 7 | { 8 | f: std::cell::UnsafeCell, 9 | res: Arr2d>, 10 | } 11 | 12 | impl Memoization2d 13 | where 14 | F: FnMut(&mut dyn Callable2, usize, usize) -> Output, 15 | { 16 | pub fn new(d1: usize, d2: usize, f: F) -> Self { 17 | Self { 18 | f: std::cell::UnsafeCell::new(f), 19 | res: Arr2d::new(d1, d2, None), 20 | } 21 | } 22 | } 23 | 24 | impl Callable2 for Memoization2d 25 | where 26 | F: FnMut(&mut dyn Callable2, usize, usize) -> Output, 27 | { 28 | fn call(&mut self, n: usize, m: usize) -> Output { 29 | match self.res[(n, m)].as_ref() { 30 | None => { 31 | let res = unsafe { (*self.f.get())(self, n, m) }; 32 | self.res[(n, m)] = Some(res.clone()); 33 | res 34 | } 35 | Some(res) => res.clone(), 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /rust/misc/run_parallel.rs: -------------------------------------------------------------------------------- 1 | use crate::io::input::Input; 2 | use crate::io::output::Output; 3 | use rayon::iter::{IndexedParallelIterator, IntoParallelRefMutIterator, ParallelIterator}; 4 | use rayon::ThreadPoolBuilder; 5 | use std::sync::atomic::AtomicUsize; 6 | 7 | pub trait ParallelJob: Sync + Send + Default + Clone { 8 | fn read_input(&mut self, input: &mut Input); 9 | fn solve(&mut self); 10 | fn write_output(&mut self, output: &mut Output, test_case: usize); 11 | } 12 | 13 | pub fn run_parallel(input: &mut Input, output: &mut Output) { 14 | let t = input.read(); 15 | let mut jobs = vec![J::default(); t]; 16 | for job in jobs.iter_mut() { 17 | job.read_input(input); 18 | } 19 | ThreadPoolBuilder::new() 20 | .stack_size(1000000000) 21 | .build_global() 22 | .unwrap(); 23 | let rem = AtomicUsize::new(t); 24 | jobs.par_iter_mut().enumerate().for_each(|(test, job)| { 25 | job.solve(); 26 | eprintln!( 27 | "Test {} done, {} remaining", 28 | test, 29 | rem.fetch_sub(1, std::sync::atomic::Ordering::Relaxed) - 1 30 | ); 31 | }); 32 | for (i, mut job) in jobs.into_iter().enumerate() { 33 | job.write_output(output, i + 1); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /c++/math/fft_double.cpp: -------------------------------------------------------------------------------- 1 | #define _USE_MATH_DEFINES 2 | #define sz(v) ((int)(v).size()) 3 | #define all(v) (v).begin(),(v).end() 4 | typedef complex base; 5 | void fft(vector &a, bool invert) { 6 | int n = sz(a); 7 | for (int i = 1, j = 0; i < n; i++) { 8 | int bit = n >> 1; 9 | for (; j >= bit; bit >>= 1) j -= bit; 10 | j += bit; 11 | if (i < j) swap(a[i], a[j]); 12 | } 13 | for (int L = 2; L <= n; L <<= 1) { 14 | long double ang = 2 * M_PI / L*(invert ? -1 : 1); 15 | base wL(cos(ang), sin(ang)); 16 | for (int i = 0; i < n; i += L) { 17 | base w(1); 18 | for (int j = 0; j < L / 2; j++) { 19 | base u = a[i + j], v = a[i + j + L / 2] * w; 20 | a[i + j] = u + v; 21 | a[i + j + L / 2] = u - v; 22 | w *= wL; 23 | } 24 | } 25 | } 26 | if (invert) { 27 | for (int i = 0; i < n; i++) a[i] /= n; 28 | } 29 | } 30 | void multiply(const vector &a, const vector &b, vector &res) { 31 | vector fa(all(a)), fb(all(b)); 32 | int n = 1; 33 | while (n < sz(a) + sz(b)) n <<= 1; 34 | fa.resize(n); fb.resize(n); 35 | fft(fa, 0); fft(fb, 0); 36 | for (int i = 0; i < n; i++) fa[i] *= fb[i]; 37 | fft(fa, 1); 38 | res.resize(n); 39 | for (int i = 0; i < n; i++) res[i] = (fa[i].real() + (fa[i].real() > 0 ? 0.5 : -0.5)); 40 | } 41 | -------------------------------------------------------------------------------- /rust/misc/memo/memoization_3d.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::md_arr::arr3d::Arr3d; 2 | use crate::misc::recursive_function::Callable3; 3 | 4 | pub struct Memoization3d 5 | where 6 | F: FnMut(&mut dyn Callable3, usize, usize, usize) -> Output, 7 | { 8 | f: std::cell::UnsafeCell, 9 | res: Arr3d>, 10 | } 11 | 12 | impl Memoization3d 13 | where 14 | F: FnMut(&mut dyn Callable3, usize, usize, usize) -> Output, 15 | { 16 | pub fn new(d1: usize, d2: usize, d3: usize, f: F) -> Self { 17 | Self { 18 | f: std::cell::UnsafeCell::new(f), 19 | res: Arr3d::new(d1, d2, d3, None), 20 | } 21 | } 22 | } 23 | 24 | impl Callable3 for Memoization3d 25 | where 26 | F: FnMut(&mut dyn Callable3, usize, usize, usize) -> Output, 27 | { 28 | fn call(&mut self, a1: usize, a2: usize, a3: usize) -> Output { 29 | match self.res[(a1, a2, a3)].as_ref() { 30 | None => { 31 | let res = unsafe { (*self.f.get())(self, a1, a2, a3) }; 32 | self.res[(a1, a2, a3)] = Some(res.clone()); 33 | res 34 | } 35 | Some(res) => res.clone(), 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /rust/graph/topological_sort.rs: -------------------------------------------------------------------------------- 1 | use crate::graph::edges::edge_trait::EdgeTrait; 2 | use crate::graph::graph::Graph; 3 | use std::collections::VecDeque; 4 | 5 | pub trait TopologicalSort { 6 | fn topological_sort(&self) -> Option>; 7 | } 8 | 9 | impl TopologicalSort for Graph { 10 | fn topological_sort(&self) -> Option> { 11 | assert!(!E::REVERSABLE); 12 | let n = self.vertex_count(); 13 | let mut res = Vec::with_capacity(n); 14 | let mut degree = vec![0u32; n]; 15 | for i in 0..n { 16 | for e in self[i].iter() { 17 | degree[e.to()] += 1; 18 | } 19 | } 20 | let mut queue = VecDeque::new(); 21 | for (i, deg) in degree.iter().enumerate() { 22 | if *deg == 0 { 23 | queue.push_back(i); 24 | } 25 | } 26 | while !queue.is_empty() { 27 | let cur = queue.pop_front().unwrap(); 28 | res.push(cur); 29 | for e in self[cur].iter() { 30 | let to = e.to(); 31 | degree[to] -= 1; 32 | if degree[to] == 0 { 33 | queue.push_back(to); 34 | } 35 | } 36 | } 37 | if res.len() == n { 38 | Some(res) 39 | } else { 40 | None 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /c++/data_stucture/eertree.cpp: -------------------------------------------------------------------------------- 1 | const int MAXN = 100005; 2 | 3 | struct NODE { 4 | int nxt[26]; //26 = # of alphabet 5 | int L, link; 6 | } tree[MAXN]; 7 | 8 | int L; 9 | char s[MAXN]; 10 | int num; // node 1 - root with L -1, node 2 - root with L 0 11 | int suff; // max suffix palindrome 12 | 13 | bool addLetter(int pos) { 14 | int cur = suff, curL = 0; 15 | int let = s[pos] - 'a'; 16 | 17 | while (true) { 18 | curL = tree[cur].L; 19 | if (pos - 1 - curL >= 0 && s[pos - 1 - curL] == s[pos]) break; 20 | cur = tree[cur].link; 21 | } 22 | if (tree[cur].nxt[let]) { 23 | suff = tree[cur].nxt[let]; 24 | return false; 25 | } 26 | 27 | num++; 28 | suff = num; 29 | tree[num].L = tree[cur].L + 2; 30 | tree[cur].nxt[let] = num; 31 | 32 | if (tree[num].L == 1) { 33 | tree[num].link = 2; 34 | return true; 35 | } 36 | 37 | while (true) { 38 | cur = tree[cur].link; 39 | curL = tree[cur].L; 40 | if (pos - 1 - curL >= 0 && s[pos - 1 - curL] == s[pos]) { 41 | tree[num].link = tree[cur].nxt[let]; 42 | break; 43 | } 44 | } 45 | return true; 46 | } 47 | 48 | void initTree() { 49 | num = 2; suff = 2; 50 | tree[1].L = -1; tree[1].link = 1; 51 | tree[2].L = 0; tree[2].link = 1; 52 | } 53 | 54 | int solve() { 55 | scanf("%s\n", &s[0]); 56 | L = strL(s); 57 | initTree(); 58 | for (int i = 0; i < L; i++) { 59 | addLetter(i); 60 | } 61 | return 0; 62 | } -------------------------------------------------------------------------------- /rust/graph/all_distances.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::md_arr::arr2d::Arr2d; 2 | use crate::collections::min_max::MinimMaxim; 3 | use crate::graph::edges::weighted_edge_trait::WeightedEdgeTrait; 4 | use crate::graph::graph::Graph; 5 | use crate::numbers::num_traits::add_sub::Addable; 6 | use crate::numbers::num_traits::ord::MinMax; 7 | use crate::numbers::num_traits::zero_one::ZeroOne; 8 | 9 | pub trait AllDistances { 10 | fn all_distances(&self) -> Arr2d; 11 | } 12 | 13 | impl> AllDistances 14 | for Graph 15 | { 16 | fn all_distances(&self) -> Arr2d { 17 | let n = self.vertex_count(); 18 | let inf = W::max_val(); 19 | let mut res = Arr2d::new(n, n, inf); 20 | for i in 0..n { 21 | res[(i, i)] = W::zero(); 22 | for e in self[i].iter() { 23 | res[(i, e.to())].minim(e.weight()); 24 | } 25 | } 26 | for k in 0..n { 27 | for i in 0..n { 28 | for j in 0..n { 29 | let r1 = res[(i, k)]; 30 | let r2 = res[(k, j)]; 31 | if r1 != inf && r2 != inf { 32 | res[(i, j)].minim(r1 + r2); 33 | } 34 | } 35 | } 36 | } 37 | res 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /rust/misc/value_ref.rs: -------------------------------------------------------------------------------- 1 | pub trait ConstValueRef { 2 | fn val() -> &'static T; 3 | } 4 | 5 | pub trait ValueRef { 6 | fn val() -> &'static T; 7 | fn set_val(t: T); 8 | fn val_mut() -> &'static mut T; 9 | } 10 | 11 | #[macro_export] 12 | macro_rules! const_value_ref { 13 | ($name: ident $val_name: ident: $int_t: ty as $ext_t: ty = $base: expr) => { 14 | const $val_name: $int_t = $base; 15 | 16 | #[derive(Copy, Clone, Eq, PartialEq, Hash)] 17 | pub struct $name {} 18 | 19 | impl $crate::misc::value_ref::ConstValueRef<$ext_t> for $name { 20 | fn val() -> &'static $ext_t { 21 | &$val_name 22 | } 23 | } 24 | }; 25 | } 26 | 27 | #[macro_export] 28 | macro_rules! value_ref { 29 | ($name: ident $val_name: ident: $t: ty) => { 30 | static mut $val_name: Option<$t> = None; 31 | 32 | #[derive(Copy, Clone, Eq, PartialEq, Hash)] 33 | struct $name {} 34 | 35 | impl $crate::misc::value_ref::ValueRef<$t> for $name { 36 | fn val() -> &'static $t { 37 | unsafe { $val_name.as_ref().unwrap() } 38 | } 39 | 40 | fn set_val(t: $t) { 41 | unsafe { 42 | $val_name = Some(t); 43 | } 44 | } 45 | 46 | fn val_mut() -> &'static mut $t { 47 | unsafe { $val_name.as_mut().unwrap() } 48 | } 49 | } 50 | }; 51 | } 52 | -------------------------------------------------------------------------------- /rust/collections/id.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::hash::Hash; 3 | use std::mem::MaybeUninit; 4 | 5 | #[derive(Default, Clone)] 6 | pub struct Id { 7 | map: HashMap, 8 | next: usize, 9 | } 10 | 11 | impl Id { 12 | pub fn new() -> Self { 13 | Self { 14 | map: HashMap::new(), 15 | next: 0, 16 | } 17 | } 18 | 19 | pub fn len(&self) -> usize { 20 | self.next 21 | } 22 | 23 | pub fn is_empty(&self) -> bool { 24 | self.len() == 0 25 | } 26 | 27 | pub fn get(&mut self, el: T) -> usize { 28 | match self.map.get(&el) { 29 | None => { 30 | let res = self.next; 31 | self.map.insert(el, res); 32 | self.next += 1; 33 | res 34 | } 35 | Some(res) => *res, 36 | } 37 | } 38 | 39 | pub fn iter(&self) -> impl Iterator { 40 | self.map.iter() 41 | } 42 | } 43 | 44 | impl Id { 45 | pub fn by_id(&self) -> Vec { 46 | unsafe { 47 | let mut res = MaybeUninit::new(Vec::with_capacity(self.len())); 48 | (*res.as_mut_ptr()).set_len(self.len()); 49 | for (val, i) in self.map.iter() { 50 | let ptr: *mut T = (*res.as_mut_ptr()).as_mut_ptr(); 51 | ptr.add(*i).write(val.clone()); 52 | } 53 | res.assume_init() 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /c++/graph/2_sat.cpp: -------------------------------------------------------------------------------- 1 | struct TwoSat { 2 | int n, var; 3 | int vcnt; 4 | vector v; 5 | void init(int var_) { 6 | var = var_; 7 | n = var_ * 2; 8 | vcnt = 0; 9 | v.clear(); v.resize(n); 10 | } 11 | int negation(int nod) { 12 | return nod >= var ? nod - var : nod + var; 13 | } 14 | // p implies q. p -> q 15 | void add(int p, int q) { 16 | graph[p].push_back(q); 17 | graph[negation(q)].push_back(negation(p)); 18 | grev[q].push_back(p); 19 | grev[negation(p)].push_back(negation(q)); 20 | } 21 | // and (p or q) 22 | void addCNF(int p, int q) { 23 | add(negation(p), q); 24 | } 25 | vector emit; 26 | void dfs1(int nod) { 27 | v[nod] = vcnt; 28 | for (int next : graph[nod]) { 29 | if (v[next] == vcnt) continue; 30 | dfs1(next); 31 | } 32 | emit.push_back(nod); 33 | } 34 | void dfs2(int nod) { 35 | v[nod] = vcnt; 36 | for (int next : grev[nod]) { 37 | if (v[next] == vcnt) continue; 38 | dfs2(next); 39 | } 40 | emit.push_back(nod); 41 | } 42 | bool solve() { 43 | vector scc_check(n); 44 | int scc_index = 0; 45 | ++vcnt; 46 | emit.clear(); 47 | for (int i = 0; i < n; i++) { 48 | if (v[i] == vcnt) continue; 49 | dfs1(i); 50 | } 51 | ++vcnt; 52 | for (auto start : vector(emit.rbegin(), emit.rend())) { 53 | if (v[start] == vcnt) continue; 54 | emit.clear(); 55 | dfs2(start); 56 | ++scc_index; 57 | for (auto node : emit) { 58 | scc_check[node] = scc_index; 59 | if (scc_check[negation(node)] == scc_index) return false; 60 | } 61 | } 62 | return true; 63 | } 64 | }; -------------------------------------------------------------------------------- /rust/numbers/number_ext.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::num_traits::add_sub::AddSub; 2 | use crate::numbers::num_traits::from_u8::FromU8; 3 | use crate::numbers::num_traits::mul_div_rem::{MulDiv, MulDivRem, Multable}; 4 | use crate::numbers::num_traits::zero_one::ZeroOne; 5 | use crate::when; 6 | use std::ops::Mul; 7 | 8 | pub trait Power { 9 | #[must_use] 10 | fn power(&self, exp: T) -> Self; 11 | } 12 | 13 | impl Power for S { 14 | fn power(&self, exp: T) -> Self { 15 | when! { 16 | exp == T::zero() => S::one(), 17 | exp % (T::one() + T::one()) == T::zero() => { 18 | let res = self.power(exp / (T::one() + T::one())); 19 | res * res 20 | }, 21 | else => self.power(exp - T::one()) * (*self), 22 | } 23 | } 24 | } 25 | 26 | pub trait NumDigs { 27 | fn num_digs(&self) -> usize; 28 | } 29 | 30 | impl NumDigs for S { 31 | fn num_digs(&self) -> usize { 32 | let mut copy = *self; 33 | let ten = S::from_u8(10); 34 | let mut res = 0; 35 | while copy != S::zero() { 36 | copy /= ten; 37 | res += 1; 38 | } 39 | res 40 | } 41 | } 42 | 43 | pub trait Square { 44 | fn square(self) -> Self; 45 | } 46 | 47 | impl + Copy> Square for T { 48 | fn square(self) -> Self { 49 | self * self 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /rust/collections/vec_ext/detuple.rs: -------------------------------------------------------------------------------- 1 | pub trait Detuple { 2 | type Res; 3 | 4 | fn detuple(self) -> Self::Res; 5 | } 6 | 7 | impl Detuple for Vec<(A, B, C, D)> { 8 | type Res = (Vec, Vec, Vec, Vec); 9 | 10 | fn detuple(self) -> Self::Res { 11 | let mut a = Vec::with_capacity(self.len()); 12 | let mut b = Vec::with_capacity(self.len()); 13 | let mut c = Vec::with_capacity(self.len()); 14 | let mut d = Vec::with_capacity(self.len()); 15 | for (aa, bb, cc, dd) in self { 16 | a.push(aa); 17 | b.push(bb); 18 | c.push(cc); 19 | d.push(dd); 20 | } 21 | (a, b, c, d) 22 | } 23 | } 24 | 25 | impl Detuple for Vec<(A, B, C)> { 26 | type Res = (Vec, Vec, Vec); 27 | 28 | fn detuple(self) -> Self::Res { 29 | let mut a = Vec::with_capacity(self.len()); 30 | let mut b = Vec::with_capacity(self.len()); 31 | let mut c = Vec::with_capacity(self.len()); 32 | for (aa, bb, cc) in self { 33 | a.push(aa); 34 | b.push(bb); 35 | c.push(cc); 36 | } 37 | (a, b, c) 38 | } 39 | } 40 | 41 | impl Detuple for Vec<(A, B)> { 42 | type Res = (Vec, Vec); 43 | 44 | fn detuple(self) -> Self::Res { 45 | let mut a = Vec::with_capacity(self.len()); 46 | let mut b = Vec::with_capacity(self.len()); 47 | for (aa, bb) in self { 48 | a.push(aa); 49 | b.push(bb); 50 | } 51 | (a, b) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /rust/misc/value.rs: -------------------------------------------------------------------------------- 1 | use std::hash::Hash; 2 | 3 | pub trait Value: Copy + Eq + Hash { 4 | fn val() -> T; 5 | } 6 | 7 | pub trait ConstValue: Value { 8 | const VAL: T; 9 | } 10 | 11 | impl> Value for V { 12 | fn val() -> T { 13 | Self::VAL 14 | } 15 | } 16 | 17 | #[macro_export] 18 | macro_rules! value { 19 | ($name: ident: $t: ty = $val: expr) => { 20 | #[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Default)] 21 | pub struct $name {} 22 | 23 | impl $crate::misc::value::ConstValue<$t> for $name { 24 | const VAL: $t = $val; 25 | } 26 | }; 27 | } 28 | 29 | pub trait DynamicValue: Value { 30 | //noinspection RsSelfConvention 31 | fn set_val(t: T); 32 | } 33 | 34 | #[macro_export] 35 | macro_rules! dynamic_value { 36 | ($name: ident: $t: ty) => { 37 | static mut VAL: Option<$t> = None; 38 | 39 | #[derive(Copy, Clone, Eq, PartialEq, Hash, Default)] 40 | struct $name {} 41 | 42 | impl $crate::misc::value::DynamicValue<$t> for $name { 43 | fn set_val(t: $t) { 44 | unsafe { 45 | VAL = Some(t); 46 | } 47 | } 48 | } 49 | 50 | impl $crate::misc::value::Value<$t> for $name { 51 | fn val() -> $t { 52 | unsafe { VAL.unwrap() } 53 | } 54 | } 55 | }; 56 | ($name: ident: $t: ty = $val: expr) => { 57 | dynamic_value!($name: $t); 58 | 59 | $name::set_val($val); 60 | }; 61 | } 62 | -------------------------------------------------------------------------------- /rust/collections/vec_ext/inc_dec.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::num_traits::add_sub::AddSub; 2 | use crate::numbers::num_traits::zero_one::ZeroOne; 3 | 4 | pub trait IncDec { 5 | #[must_use] 6 | fn inc(self) -> Self; 7 | #[must_use] 8 | fn dec(self) -> Self; 9 | } 10 | 11 | impl IncDec for Vec { 12 | fn inc(mut self) -> Self { 13 | self.iter_mut().for_each(|i| *i += T::one()); 14 | self 15 | } 16 | 17 | fn dec(mut self) -> Self { 18 | self.iter_mut().for_each(|i| *i -= T::one()); 19 | self 20 | } 21 | } 22 | 23 | impl IncDec for Vec<(T, U)> { 24 | fn inc(mut self) -> Self { 25 | self.iter_mut().for_each(|(i, j)| { 26 | *i += T::one(); 27 | *j += U::one(); 28 | }); 29 | self 30 | } 31 | 32 | fn dec(mut self) -> Self { 33 | self.iter_mut().for_each(|(i, j)| { 34 | *i -= T::one(); 35 | *j -= U::one(); 36 | }); 37 | self 38 | } 39 | } 40 | 41 | impl IncDec for Vec<(T, U, V)> { 42 | fn inc(mut self) -> Self { 43 | self.iter_mut().for_each(|(i, j, k)| { 44 | *i += T::one(); 45 | *j += U::one(); 46 | *k += V::one(); 47 | }); 48 | self 49 | } 50 | 51 | fn dec(mut self) -> Self { 52 | self.iter_mut().for_each(|(i, j, k)| { 53 | *i -= T::one(); 54 | *j -= U::one(); 55 | *k -= V::one(); 56 | }); 57 | self 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /rust/string/string_algorithms/palindromes.rs: -------------------------------------------------------------------------------- 1 | use crate::string::slicelike::Slicelike; 2 | 3 | pub trait Palindromes { 4 | fn odd_palindromes(&self) -> Vec; 5 | fn even_palindromes(&self) -> Vec; 6 | } 7 | 8 | impl Palindromes for S 9 | where 10 | S::Output: PartialEq + Sized, 11 | { 12 | fn odd_palindromes(&self) -> Vec { 13 | let mut res: Vec = Vec::with_capacity(self.len()); 14 | let mut l = 0; 15 | let mut r = 0; 16 | for i in 0..self.len() { 17 | let mut k = if i >= r { 18 | 1 19 | } else { 20 | res[l + r - 1 - i].min(r - i) 21 | }; 22 | while i + k < self.len() && i >= k && self[i + k] == self[i - k] { 23 | k += 1; 24 | } 25 | res.push(k); 26 | if i + k > r { 27 | l = i + 1 - k; 28 | r = i + k; 29 | } 30 | } 31 | res 32 | } 33 | 34 | fn even_palindromes(&self) -> Vec { 35 | let mut res: Vec = Vec::with_capacity(self.len()); 36 | let mut l = 0; 37 | let mut r = 0; 38 | for i in 0..self.len() { 39 | let mut k = if i >= r { 0 } else { res[l + r - i].min(r - i) }; 40 | while i + k < self.len() && i > k && self[i + k] == self[i - k - 1] { 41 | k += 1; 42 | } 43 | res.push(k); 44 | if i + k > r { 45 | l = i - k; 46 | r = i + k; 47 | } 48 | } 49 | res 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /rust/misc/memo/memoization_4d.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::md_arr::arr4d::Arr4d; 2 | use crate::misc::recursive_function::Callable4; 3 | 4 | pub struct Memoization4d 5 | where 6 | F: FnMut( 7 | &mut dyn Callable4, 8 | usize, 9 | usize, 10 | usize, 11 | usize, 12 | ) -> Output, 13 | { 14 | f: std::cell::UnsafeCell, 15 | res: Arr4d>, 16 | } 17 | 18 | impl Memoization4d 19 | where 20 | F: FnMut( 21 | &mut dyn Callable4, 22 | usize, 23 | usize, 24 | usize, 25 | usize, 26 | ) -> Output, 27 | { 28 | pub fn new(d1: usize, d2: usize, d3: usize, d4: usize, f: F) -> Self { 29 | Self { 30 | f: std::cell::UnsafeCell::new(f), 31 | res: Arr4d::new(d1, d2, d3, d4, None), 32 | } 33 | } 34 | } 35 | 36 | impl Callable4 for Memoization4d 37 | where 38 | F: FnMut( 39 | &mut dyn Callable4, 40 | usize, 41 | usize, 42 | usize, 43 | usize, 44 | ) -> Output, 45 | { 46 | fn call(&mut self, a1: usize, a2: usize, a3: usize, a4: usize) -> Output { 47 | match self.res[(a1, a2, a3, a4)].as_ref() { 48 | None => { 49 | let res = unsafe { (*self.f.get())(self, a1, a2, a3, a4) }; 50 | self.res[(a1, a2, a3, a4)] = Some(res.clone()); 51 | res 52 | } 53 | Some(res) => res.clone(), 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /c++/data_stucture/seg_lazy.cpp: -------------------------------------------------------------------------------- 1 | // example implementation of sum tree 2 | const int TSIZE = 131072; // always 2^k form && n <= TSIZE 3 | int segtree[TSIZE * 2], prop[TSIZE * 2]; 4 | void seg_init(int nod, int l, int r) { 5 | if (l == r) segtree[nod] = dat[l]; 6 | else { 7 | int m = (l + r) >> 1; 8 | seg_init(nod << 1, l, m); 9 | seg_init(nod << 1 | 1, m + 1, r); 10 | segtree[nod] = segtree[nod << 1] + segtree[nod << 1 | 1]; 11 | } 12 | } 13 | void seg_relax(int nod, int l, int r) { 14 | if (prop[nod] == 0) return; 15 | if (l < r) { 16 | int m = (l + r) >> 1; 17 | segtree[nod << 1] += (m - l + 1) * prop[nod]; 18 | prop[nod << 1] += prop[nod]; 19 | segtree[nod << 1 | 1] += (r - m) * prop[nod]; 20 | prop[nod << 1 | 1] += prop[nod]; 21 | } 22 | prop[nod] = 0; 23 | } 24 | int seg_query(int nod, int l, int r, int s, int e) { 25 | if (r < s || e < l) return 0; 26 | if (s <= l && r <= e) return segtree[nod]; 27 | seg_relax(nod, l, r); 28 | int m = (l + r) >> 1; 29 | return seg_query(nod << 1, l, m, s, e) + seg_query(nod << 1 | 1, m + 1, r, s, e); 30 | } 31 | void seg_update(int nod, int l, int r, int s, int e, int val) { 32 | if (r < s || e < l) return; 33 | if (s <= l && r <= e) { 34 | segtree[nod] += (r - l + 1) * val; 35 | prop[nod] += val; 36 | return; 37 | } 38 | seg_relax(nod, l, r); 39 | int m = (l + r) >> 1; 40 | seg_update(nod << 1, l, m, s, e, val); 41 | seg_update(nod << 1 | 1, m + 1, r, s, e, val); 42 | segtree[nod] = segtree[nod << 1] + segtree[nod << 1 | 1]; 43 | } 44 | // usage: 45 | // seg_update(1, 0, n - 1, qs, qe, val); 46 | // seg_query(1, 0, n - 1, qs, qe); -------------------------------------------------------------------------------- /rust/numbers/interpolation.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::mod_int::BaseModInt; 2 | use crate::numbers::mod_utils::inverse_factorials; 3 | use crate::numbers::num_traits::as_index::AsIndex; 4 | 5 | pub struct Interpolation { 6 | values: Vec, 7 | coef: Vec, 8 | } 9 | 10 | impl Interpolation 11 | where 12 | Mod::T: AsIndex, 13 | { 14 | pub fn new(values: Vec) -> Self { 15 | let n = values.len(); 16 | Self::with_inverse_factorials(values, inverse_factorials(n).as_slice()) 17 | } 18 | 19 | pub fn with_inverse_factorials(values: Vec, inv_fact: &[Mod]) -> Self { 20 | let n = values.len(); 21 | let mut coef = Vec::with_capacity(n); 22 | for (i, &v) in values.iter().enumerate() { 23 | coef.push( 24 | v * inv_fact[i] 25 | * inv_fact[n - i - 1] 26 | * if (n - i - 1) & 1 == 1 { 27 | -Mod::one() 28 | } else { 29 | Mod::one() 30 | }, 31 | ); 32 | } 33 | Self { values, coef } 34 | } 35 | 36 | pub fn calculate(&self, x: Mod) -> Mod { 37 | let i = x.to_index(); 38 | if i < self.values.len() { 39 | return self.values[i]; 40 | } 41 | let mut product = Mod::one(); 42 | for j in 0..self.values.len() { 43 | product *= x - Mod::from_index(j); 44 | } 45 | let mut res = Mod::zero(); 46 | for (i, &c) in self.coef.iter().enumerate() { 47 | res += c * (x - Mod::from_index(i)).inv().unwrap(); 48 | } 49 | res * product 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /c++/graph/Minimum General Weighted Matching.cpp: -------------------------------------------------------------------------------- 1 | // Minimum General Weighted Matching (Perfect Match) by PECaveros 2 | struct MGWM { 3 | static const int MXN = 105; 4 | int n, edge[MXN][MXN]; 5 | int match[MXN], dis[MXN], onstk[MXN]; 6 | vector stk; 7 | void init(int _n) { 8 | n = _n; 9 | for (int i = 0; i < n; i++) 10 | for (int j = 0; j < n; j++) 11 | edge[i][j] = 0; 12 | } 13 | void add_edge(int u, int v, int w) 14 | { 15 | edge[u][v] = edge[v][u] = w; 16 | } 17 | bool SPFA(int u) { 18 | if (onstk[u]) return true; 19 | stk.PB(u); 20 | onstk[u] = 1; 21 | for (int v = 0; v dis[u] - edge[v][m] + edge[u][v]) { 25 | dis[m] = dis[u] - edge[v][m] + edge[u][v]; 26 | onstk[v] = 1; 27 | stk.PB(v); 28 | if (SPFA(m)) return true; 29 | stk.pop_back(); 30 | onstk[v] = 0; 31 | } 32 | } 33 | } 34 | onstk[u] = 0; 35 | stk.pop_back(); 36 | return false; 37 | } 38 | int solve() { 39 | // find a match 40 | for (int i = 0; i= 2) { 53 | int u = stk.back(); stk.pop_back(); 54 | int v = stk.back(); stk.pop_back(); 55 | match[u] = v; 56 | match[v] = u; 57 | } 58 | } 59 | } 60 | if (!found) break; 61 | } 62 | int ret = 0; 63 | for (int i = 0; i (Vec, Vec); 6 | 7 | fn dfs_order(&self) -> (Vec, Vec) { 8 | self.dfs_order_with_root(0) 9 | } 10 | } 11 | 12 | impl DFSOrder for Graph { 13 | fn dfs_order_with_root(&self, root: usize) -> (Vec, Vec) { 14 | debug_assert!(self.is_tree()); 15 | let count = self.vertex_count(); 16 | let mut position = vec![0; count]; 17 | let mut end = vec![0; count]; 18 | let mut edge = vec![0u32; count]; 19 | let mut stack = vec![0u32; count]; 20 | let mut last = vec![0u32; count]; 21 | let mut size = 1usize; 22 | last[root] = root as u32; 23 | stack[0] = root as u32; 24 | position[root] = 0; 25 | let mut index = 0usize; 26 | while size > 0 { 27 | let current = stack[size - 1] as usize; 28 | let c_edge = &mut edge[current]; 29 | if *c_edge == self[current].len() as u32 { 30 | end[current] = index + 1; 31 | size -= 1; 32 | } else { 33 | let next = self[current][*c_edge as usize].to(); 34 | *c_edge += 1; 35 | if next == (last[current] as usize) { 36 | continue; 37 | } 38 | index += 1; 39 | position[next] = index; 40 | last[next] = current as u32; 41 | stack[size] = next as u32; 42 | size += 1; 43 | } 44 | } 45 | (position, end) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /rust/collections/dsu2d.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::dsu::DSU; 2 | use crate::collections::iter_ext::collect::IterCollect; 3 | use std::ops::{Deref, DerefMut}; 4 | 5 | #[derive(Clone)] 6 | pub struct DSU2d { 7 | inner: DSU, 8 | cols: usize, 9 | } 10 | 11 | impl Deref for DSU2d { 12 | type Target = DSU; 13 | 14 | fn deref(&self) -> &Self::Target { 15 | &self.inner 16 | } 17 | } 18 | 19 | impl DerefMut for DSU2d { 20 | fn deref_mut(&mut self) -> &mut Self::Target { 21 | &mut self.inner 22 | } 23 | } 24 | 25 | impl DSU2d { 26 | pub fn new(rows: usize, cols: usize) -> Self { 27 | Self { 28 | inner: DSU::new(rows * cols), 29 | cols, 30 | } 31 | } 32 | 33 | pub fn size(&self, row: usize, col: usize) -> usize { 34 | self.inner.size(row * self.cols + col) 35 | } 36 | 37 | pub fn iter(&self) -> impl Iterator + '_ { 38 | let cols = self.cols; 39 | self.inner.iter().map(move |i| (i / cols, i % cols)) 40 | } 41 | 42 | pub fn join(&mut self, r1: usize, c1: usize, r2: usize, c2: usize) -> bool { 43 | self.inner.join(r1 * self.cols + c1, r2 * self.cols + c2) 44 | } 45 | 46 | pub fn get(&self, row: usize, col: usize) -> (usize, usize) { 47 | let res = self.inner.get(row * self.cols + col); 48 | (res / self.cols, res % self.cols) 49 | } 50 | 51 | pub fn parts(&self) -> Vec> { 52 | self.inner 53 | .parts() 54 | .into_iter() 55 | .map(|v| { 56 | v.into_iter() 57 | .map(|i| (i / self.cols, i % self.cols)) 58 | .collect_vec() 59 | }) 60 | .collect_vec() 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /rust/numbers/num_utils.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::num_traits::add_sub::AddSub; 2 | use crate::numbers::num_traits::as_index::AsIndex; 3 | use crate::numbers::num_traits::mul_div_rem::Multable; 4 | use crate::numbers::num_traits::zero_one::ZeroOne; 5 | use std::ops::{Add, Div}; 6 | 7 | pub fn factorials(len: usize) -> Vec { 8 | let mut res = Vec::new(); 9 | if len > 0 { 10 | res.push(T::one()); 11 | } 12 | while res.len() < len { 13 | res.push((*res.last().unwrap()) * T::from_index(res.len())); 14 | } 15 | res 16 | } 17 | 18 | pub fn powers(base: T, len: usize) -> Vec { 19 | let mut res = Vec::new(); 20 | if len > 0 { 21 | res.push(T::one()); 22 | } 23 | while res.len() < len { 24 | res.push((*res.last().unwrap()) * base); 25 | } 26 | res 27 | } 28 | 29 | pub fn factorial(n: usize) -> T { 30 | let mut res = T::one(); 31 | for i in 1..=n { 32 | res *= T::from_index(i); 33 | } 34 | res 35 | } 36 | 37 | pub trait PartialSums { 38 | fn partial_sums(&self) -> Vec; 39 | } 40 | 41 | impl + Copy> PartialSums for [T] { 42 | fn partial_sums(&self) -> Vec { 43 | let mut res = Vec::with_capacity(self.len() + 1); 44 | res.push(T::zero()); 45 | for i in self.iter() { 46 | res.push(*res.last().unwrap() + *i); 47 | } 48 | res 49 | } 50 | } 51 | 52 | pub trait UpperDiv { 53 | fn upper_div(self, other: Self) -> Self; 54 | } 55 | 56 | impl + AddSub + ZeroOne + Copy> UpperDiv for T { 57 | fn upper_div(self, other: Self) -> Self { 58 | (self + other - Self::one()) / other 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /rust/numbers/multiplicative_function.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::number_ext::Power; 2 | use crate::numbers::primes::factorize::Factorize; 3 | use crate::numbers::primes::sieve::divisor_table; 4 | 5 | pub struct MulitplicativeFunction(Box i64>); 6 | 7 | impl MulitplicativeFunction { 8 | pub fn new(f: impl Fn(i64, usize, i64) -> i64 + 'static) -> Self { 9 | Self(Box::new(f)) 10 | } 11 | 12 | pub fn call(&self, arg: i64) -> i64 { 13 | let mut res = 1; 14 | let d = arg.prime_divisors(); 15 | for (p, q) in d { 16 | res *= self.0(p, q, p.power(q)); 17 | } 18 | res 19 | } 20 | 21 | pub fn calculate_up_to(&self, n: usize) -> Vec { 22 | let divisor_table = divisor_table::(n); 23 | let mut res = Vec::with_capacity(n); 24 | if n >= 1 { 25 | res.push(0); 26 | } 27 | if n <= 1 { 28 | return res; 29 | } 30 | res.push(1); 31 | for (i, d) in divisor_table.into_iter().enumerate().skip(2) { 32 | let mut j = i; 33 | let mut exp = 0; 34 | while j % d == 0 { 35 | j /= d; 36 | exp += 1; 37 | } 38 | res.push(res[j] * self.0(d as i64, exp, (i / j) as i64)); 39 | } 40 | res 41 | } 42 | 43 | pub fn divisor_count() -> Self { 44 | Self::new(|_, exp, _| exp as i64 + 1) 45 | } 46 | 47 | pub fn divisor_sum() -> Self { 48 | Self::new(|p, _, pow| (pow * p - 1) / (p - 1)) 49 | } 50 | 51 | pub fn phi() -> Self { 52 | Self::new(|p, _, pow| pow / p * (p - 1)) 53 | } 54 | 55 | pub fn mobius() -> Self { 56 | Self::new(|_, exp, _| if exp == 1 { -1 } else { 0 }) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /rust/misc/memo/memoization_5d.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::md_arr::arr5d::Arr5d; 2 | use crate::misc::recursive_function::Callable5; 3 | 4 | pub struct Memoization5d 5 | where 6 | F: FnMut( 7 | &mut dyn Callable5, 8 | usize, 9 | usize, 10 | usize, 11 | usize, 12 | usize, 13 | ) -> Output, 14 | { 15 | f: std::cell::UnsafeCell, 16 | res: Arr5d>, 17 | } 18 | 19 | impl Memoization5d 20 | where 21 | F: FnMut( 22 | &mut dyn Callable5, 23 | usize, 24 | usize, 25 | usize, 26 | usize, 27 | usize, 28 | ) -> Output, 29 | { 30 | pub fn new(d1: usize, d2: usize, d3: usize, d4: usize, d5: usize, f: F) -> Self { 31 | Self { 32 | f: std::cell::UnsafeCell::new(f), 33 | res: Arr5d::new(d1, d2, d3, d4, d5, None), 34 | } 35 | } 36 | } 37 | 38 | impl Callable5 39 | for Memoization5d 40 | where 41 | F: FnMut( 42 | &mut dyn Callable5, 43 | usize, 44 | usize, 45 | usize, 46 | usize, 47 | usize, 48 | ) -> Output, 49 | { 50 | fn call(&mut self, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) -> Output { 51 | match self.res[(a1, a2, a3, a4, a5)].as_ref() { 52 | None => { 53 | let res = unsafe { (*self.f.get())(self, a1, a2, a3, a4, a5) }; 54 | self.res[(a1, a2, a3, a4, a5)] = Some(res.clone()); 55 | res 56 | } 57 | Some(res) => res.clone(), 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /rust/collections/fast_clear_fenwick.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::min_max::MinimMaxim; 2 | use crate::numbers::num_traits::add_sub::AddSub; 3 | use crate::numbers::num_traits::zero_one::ZeroOne; 4 | 5 | #[derive(Clone)] 6 | pub struct FastClearFenwickTree { 7 | value: Vec<(u32, T)>, 8 | epoch: u32, 9 | } 10 | 11 | impl FastClearFenwickTree { 12 | pub fn new(size: usize) -> Self { 13 | Self { 14 | value: vec![(0, T::zero()); size], 15 | epoch: 0, 16 | } 17 | } 18 | 19 | pub fn get_to(&self, mut to: usize) -> T { 20 | to.minim(self.value.len()); 21 | let mut result = T::zero(); 22 | while to > 0 { 23 | to -= 1; 24 | if self.value[to].0 == self.epoch { 25 | result += self.value[to].1; 26 | } 27 | to &= to + 1; 28 | } 29 | result 30 | } 31 | 32 | pub fn get(&self, from: usize, to: usize) -> T { 33 | if from >= to { 34 | T::zero() 35 | } else { 36 | self.get_to(to) - self.get_to(from) 37 | } 38 | } 39 | 40 | pub fn add(&mut self, mut at: usize, v: T) { 41 | while at < self.value.len() { 42 | if self.value[at].0 != self.epoch { 43 | self.value[at].0 = self.epoch; 44 | self.value[at].1 = T::zero(); 45 | } 46 | self.value[at].1 += v; 47 | at |= at + 1; 48 | } 49 | } 50 | 51 | pub fn iter(&self) -> impl Iterator + '_ { 52 | self.value 53 | .iter() 54 | .enumerate() 55 | // edition 2021 56 | .map(move |(i, _)| self.get(i, i + 1)) 57 | } 58 | 59 | pub fn clear(&mut self) { 60 | self.epoch += 1; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /c++/graph/bipartite-matching-hopcroft.cpp: -------------------------------------------------------------------------------- 1 | // in: n, m, graph 2 | // out: match, matched 3 | // vertex cover: (reached[0][left_node] == 0) || (reached[1][right_node] == 1) 4 | // O(E*sqrt(V)) 5 | struct BipartiteMatching { 6 | int n, m; 7 | vector> graph; 8 | vector matched, match, edgeview, level; 9 | vector reached[2]; 10 | BipartiteMatching() {} 11 | BipartiteMatching(int n, int m) : n(n), m(m), graph(n), matched(m, -1), match(n, -1) {} 12 | bool assignLevel() { 13 | bool reachable = false; 14 | level.assign(n, -1); 15 | reached[0].assign(n, 0); 16 | reached[1].assign(m, 0); 17 | queue q; 18 | for (int i = 0; i < n; i++) { 19 | if (match[i] == -1) { 20 | level[i] = 0; 21 | reached[0][i] = 1; 22 | q.push(i); 23 | } 24 | } 25 | while (!q.empty()) { 26 | auto cur = q.front(); q.pop(); 27 | for (auto adj : graph[cur]) { 28 | reached[1][adj] = 1; 29 | auto next = matched[adj]; 30 | if (next == -1) { 31 | reachable = true; 32 | } 33 | else if (level[next] == -1) { 34 | level[next] = level[cur] + 1; 35 | reached[0][next] = 1; 36 | q.push(next); 37 | } 38 | } 39 | } 40 | return reachable; 41 | } 42 | int findpath(int nod) { 43 | for (int &i = edgeview[nod]; i < graph[nod].size(); i++) { 44 | int adj = graph[nod][i]; 45 | int next = matched[adj]; 46 | if (next >= 0 && level[next] != level[nod] + 1) continue; 47 | if (next == -1 || findpath(next)) { 48 | match[nod] = adj; 49 | matched[adj] = nod; 50 | return 1; 51 | } 52 | } 53 | return 0; 54 | } 55 | 56 | int solve() { 57 | int ans = 0; 58 | while (assignLevel()) { 59 | edgeview.assign(n, 0); 60 | for (int i = 0; i < n; i++) 61 | if (match[i] == -1) 62 | ans += findpath(i); 63 | } 64 | return ans; 65 | } 66 | }; 67 | -------------------------------------------------------------------------------- /rust/numbers/number_iterator.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::num_traits::add_sub::Addable; 2 | use crate::numbers::num_traits::from_u8::FromU8; 3 | use crate::numbers::num_traits::mul_div_rem::MulDiv; 4 | use crate::numbers::num_traits::ord::MinMax; 5 | use crate::numbers::num_traits::zero_one::ZeroOne; 6 | 7 | pub fn iterate( 8 | from: T, 9 | to: T, 10 | ) -> Vec<(T, usize, T)> { 11 | iterate_with_base(from, to, T::from_u8(10)) 12 | } 13 | 14 | pub fn iterate_with_base( 15 | mut from: T, 16 | mut to: T, 17 | base: T, 18 | ) -> Vec<(T, usize, T)> { 19 | let mut pw = T::one(); 20 | to += T::one(); 21 | let mut res = Vec::new(); 22 | let mut i = 0usize; 23 | loop { 24 | let end = T::max_val() / base < pw || from / (pw * base) == to / (pw * base); 25 | if end { 26 | let c_from = from / pw; 27 | let c_to = to / pw; 28 | let mut cur = c_from; 29 | while cur < c_to { 30 | res.push((cur, i, cur * pw)); 31 | cur += T::one(); 32 | } 33 | break; 34 | } 35 | let c_from = from / pw; 36 | let c_to = (from / (pw * base) + T::one()) * base; 37 | let mut cur = c_from; 38 | while cur < c_to { 39 | res.push((cur, i, cur * pw)); 40 | cur += T::one(); 41 | } 42 | from = c_to * pw; 43 | let c_from = to / (pw * base) * base; 44 | let c_to = to / pw; 45 | let mut cur = c_from; 46 | while cur < c_to { 47 | res.push((cur, i, cur * pw)); 48 | cur += T::one(); 49 | } 50 | i += 1; 51 | pw *= base; 52 | } 53 | res.sort_by(|a, b| a.2.cmp(&b.2)); 54 | res 55 | } 56 | -------------------------------------------------------------------------------- /rust/misc/hungarian_algorithm.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::bit_set::BitSet; 2 | use crate::collections::legacy_fill::LegacyFill; 3 | use crate::collections::md_arr::arr2d::Arr2d; 4 | use crate::numbers::num_traits::ord::MinMax; 5 | 6 | pub fn hungarian_algorithm(a: &Arr2d) -> i64 { 7 | assert_eq!(a.d1(), a.d2()); 8 | let inf = i64::max_val() / 2; 9 | let n = a.d1(); 10 | let mut u = vec![0; n + 1]; 11 | let mut v = vec![0; n + 1]; 12 | let mut p = vec![n; n + 1]; 13 | let mut way = vec![n; n + 1]; 14 | let mut min_v = vec![inf; n + 1]; 15 | let mut used = BitSet::new(n + 1); 16 | for i in 0..n { 17 | p[n] = i; 18 | let mut j0 = n; 19 | used.fill(false); 20 | min_v.legacy_fill(inf); 21 | while p[j0] != n { 22 | used.set(j0); 23 | let i0 = p[j0]; 24 | let mut delta = inf; 25 | let mut j1 = n; 26 | for j in 0..n { 27 | if !used[j] { 28 | let cur = a[(i0, j)] - u[i0] - v[j]; 29 | if cur < min_v[j] { 30 | min_v[j] = cur; 31 | way[j] = j0; 32 | } 33 | if min_v[j] < delta { 34 | delta = min_v[j]; 35 | j1 = j; 36 | } 37 | } 38 | } 39 | for j in 0..=n { 40 | if used[j] { 41 | u[p[j]] += delta; 42 | v[j] -= delta; 43 | } else { 44 | min_v[j] -= delta; 45 | } 46 | } 47 | j0 = j1; 48 | } 49 | while j0 != n { 50 | let j1 = way[j0]; 51 | p[j0] = p[j1]; 52 | j0 = j1; 53 | } 54 | } 55 | -v[n] 56 | } 57 | -------------------------------------------------------------------------------- /rust/graph/bridges.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::bit_set::BitSet; 2 | use crate::collections::min_max::MinimMaxim; 3 | use crate::graph::edges::edge_trait::EdgeTrait; 4 | use crate::graph::graph::Graph; 5 | use crate::misc::recursive_function::{Callable2, RecursiveFunction2}; 6 | 7 | pub trait BridgeSearch { 8 | fn bridges(&self) -> Vec<(usize, usize)>; 9 | } 10 | 11 | impl BridgeSearch for Graph { 12 | fn bridges(&self) -> Vec<(usize, usize)> { 13 | assert!(E::REVERSABLE); 14 | let n = self.vertex_count(); 15 | let mut timer = 0; 16 | let mut tin = vec![0; n]; 17 | let mut fup = vec![0; n]; 18 | let mut used = BitSet::new(n); 19 | let mut ans = Vec::new(); 20 | for i in 0..n { 21 | if !used[i] { 22 | let mut dfs = RecursiveFunction2::new(|f, vert: usize, prev: usize| { 23 | used.set(vert); 24 | tin[vert] = timer; 25 | fup[vert] = timer; 26 | timer += 1; 27 | for e in &self[vert] { 28 | if e.to() == prev { 29 | continue; 30 | } 31 | let to = e.to(); 32 | if used[to] { 33 | fup[vert].minim(tin[to]); 34 | } else { 35 | f.call(to, vert); 36 | let cand = fup[to]; 37 | fup[vert].minim(cand); 38 | if fup[to] > tin[vert] { 39 | ans.push((vert, to)); 40 | } 41 | } 42 | } 43 | }); 44 | dfs.call(i, i); 45 | } 46 | } 47 | ans 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /rust/collections/slice_ext/bounds.rs: -------------------------------------------------------------------------------- 1 | pub trait Bounds { 2 | fn lower_bound(&self, el: &T) -> usize; 3 | fn upper_bound(&self, el: &T) -> usize; 4 | fn bin_search(&self, el: &T) -> Option; 5 | fn more(&self, el: &T) -> usize; 6 | fn more_or_eq(&self, el: &T) -> usize; 7 | fn less(&self, el: &T) -> usize; 8 | fn less_or_eq(&self, el: &T) -> usize; 9 | } 10 | 11 | impl Bounds for [T] { 12 | fn lower_bound(&self, el: &T) -> usize { 13 | let mut left = 0; 14 | let mut right = self.len(); 15 | while left < right { 16 | let mid = left + ((right - left) >> 1); 17 | if &self[mid] < el { 18 | left = mid + 1; 19 | } else { 20 | right = mid; 21 | } 22 | } 23 | left 24 | } 25 | 26 | fn upper_bound(&self, el: &T) -> usize { 27 | let mut left = 0; 28 | let mut right = self.len(); 29 | while left < right { 30 | let mid = left + ((right - left) >> 1); 31 | if &self[mid] <= el { 32 | left = mid + 1; 33 | } else { 34 | right = mid; 35 | } 36 | } 37 | left 38 | } 39 | 40 | fn bin_search(&self, el: &T) -> Option { 41 | let at = self.lower_bound(el); 42 | if at == self.len() || &self[at] != el { 43 | None 44 | } else { 45 | Some(at) 46 | } 47 | } 48 | 49 | fn more(&self, el: &T) -> usize { 50 | self.len() - self.upper_bound(el) 51 | } 52 | 53 | fn more_or_eq(&self, el: &T) -> usize { 54 | self.len() - self.lower_bound(el) 55 | } 56 | 57 | fn less(&self, el: &T) -> usize { 58 | self.lower_bound(el) 59 | } 60 | 61 | fn less_or_eq(&self, el: &T) -> usize { 62 | self.upper_bound(el) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /rust/graph/edges/edge.rs: -------------------------------------------------------------------------------- 1 | use crate::graph::edges::edge_id::{EdgeId, NoId, WithId}; 2 | use crate::graph::edges::edge_trait::EdgeTrait; 3 | use crate::graph::graph::Graph; 4 | use crate::io::input::{Input, Readable}; 5 | 6 | #[derive(Clone)] 7 | pub struct EdgeRaw { 8 | to: u32, 9 | id: Id, 10 | } 11 | 12 | impl EdgeRaw { 13 | pub fn new(to: usize) -> Self { 14 | Self { 15 | to: to as u32, 16 | id: Id::new(), 17 | } 18 | } 19 | } 20 | 21 | impl EdgeTrait for EdgeRaw { 22 | const REVERSABLE: bool = false; 23 | 24 | fn to(&self) -> usize { 25 | self.to as usize 26 | } 27 | 28 | fn id(&self) -> usize { 29 | self.id.id() 30 | } 31 | 32 | fn set_id(&mut self, id: usize) { 33 | self.id.set_id(id); 34 | } 35 | 36 | fn reverse_id(&self) -> usize { 37 | panic!("no reverse") 38 | } 39 | 40 | fn set_reverse_id(&mut self, _: usize) { 41 | panic!("no reverse") 42 | } 43 | 44 | fn reverse_edge(&self, _: usize) -> Self { 45 | panic!("no reverse") 46 | } 47 | } 48 | 49 | pub type Edge = EdgeRaw; 50 | pub type EdgeWithId = EdgeRaw; 51 | 52 | pub trait ReadEdgeGraph { 53 | fn read_graph(&mut self, n: usize, m: usize) -> Graph>; 54 | } 55 | 56 | impl ReadEdgeGraph for Input<'_> { 57 | fn read_graph(&mut self, n: usize, m: usize) -> Graph> { 58 | let mut graph = Graph::new(n); 59 | for _ in 0..m { 60 | graph.add_edge(self.read(), EdgeRaw::new(self.read())); 61 | } 62 | graph 63 | } 64 | } 65 | 66 | impl Readable for Graph> { 67 | fn read(input: &mut Input) -> Self { 68 | let n = input.read(); 69 | let m = input.read(); 70 | ::read_graph(input, n, m) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /rust/graph/distances.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::indexed_heap::IndexedHeap; 2 | use crate::graph::edges::weighted_edge_trait::WeightedEdgeTrait; 3 | use crate::graph::graph::Graph; 4 | use crate::numbers::num_traits::add_sub::Addable; 5 | use crate::numbers::num_traits::zero_one::ZeroOne; 6 | 7 | pub trait Distances { 8 | fn distances_from(&self, source: usize) -> Vec>; 9 | 10 | fn distance(&self, source: usize, mut destination: usize) -> Option<(W, Vec<(usize, usize)>)> { 11 | let dist = self.distances_from(source); 12 | dist[destination].map(|(w, ..)| { 13 | let mut path = Vec::new(); 14 | while destination != source { 15 | let (_, from, edge) = dist[destination].unwrap(); 16 | path.push((from, edge)); 17 | destination = from; 18 | } 19 | path.reverse(); 20 | (w, path) 21 | }) 22 | } 23 | } 24 | 25 | impl> Distances for Graph { 26 | fn distances_from(&self, source: usize) -> Vec> { 27 | let n = self.vertex_count(); 28 | let mut res = vec![None; n]; 29 | let mut heap = IndexedHeap::new(n); 30 | heap.add_or_adjust(source, (W::zero(), source, self[source].len())); 31 | while let Some((cur, dist)) = heap.pop() { 32 | res[cur] = Some(dist); 33 | let dist = dist.0; 34 | for (i, e) in self[cur].iter().enumerate() { 35 | let next = e.to(); 36 | if res[next].is_some() { 37 | continue; 38 | } 39 | let total = dist + e.weight(); 40 | let next_dist = (total, cur, i); 41 | heap.add_or_relax(next, next_dist); 42 | } 43 | } 44 | res 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /rust/numbers/mod_utils.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::mod_int::BaseModInt; 2 | use crate::numbers::num_traits::as_index::AsIndex; 3 | use crate::numbers::num_utils::factorials; 4 | 5 | pub fn inverses(len: usize) -> Vec 6 | where 7 | M::T: AsIndex, 8 | { 9 | let mut res = Vec::new(); 10 | if len > 0 { 11 | res.push(M::zero()); 12 | } 13 | if len > 1 { 14 | res.push(M::one()); 15 | } 16 | while res.len() < len { 17 | res.push( 18 | res[M::module().to_index() % res.len()] 19 | * (M::from(M::module() / (M::T::from_index(res.len()))).neg()), 20 | ); 21 | } 22 | res 23 | } 24 | 25 | pub fn inverse_factorials(len: usize) -> Vec 26 | where 27 | M::T: AsIndex, 28 | { 29 | let mut res = inverses(len); 30 | if len > 0 { 31 | res[0] = M::one(); 32 | } 33 | for i in 1..len { 34 | let last = res[i - 1]; 35 | res[i] *= last; 36 | } 37 | res 38 | } 39 | 40 | pub struct Combinations 41 | where 42 | M::T: AsIndex, 43 | { 44 | fact: Vec, 45 | inv_fact: Vec, 46 | } 47 | 48 | impl Combinations 49 | where 50 | M::T: AsIndex, 51 | { 52 | pub fn new(len: usize) -> Self { 53 | Self { 54 | fact: factorials(len), 55 | inv_fact: inverse_factorials(len), 56 | } 57 | } 58 | 59 | pub fn c(&self, n: usize, k: usize) -> M { 60 | if n < k { 61 | M::zero() 62 | } else { 63 | self.fact[n] * self.inv_fact[k] * self.inv_fact[n - k] 64 | } 65 | } 66 | 67 | pub fn c_inv(&self, n: usize, k: usize) -> M { 68 | self.inv_fact[n] * self.fact[k] * self.fact[n - k] 69 | } 70 | 71 | pub fn fact(&self, n: usize) -> M { 72 | self.fact[n] 73 | } 74 | 75 | pub fn inv_fact(&self, n: usize) -> M { 76 | self.inv_fact[n] 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /c++/graph/bcc.cpp: -------------------------------------------------------------------------------- 1 | const int MAXN = 100; 2 | vector> graph[MAXN]; // { next vertex id, edge id } 3 | int up[MAXN], visit[MAXN], vtime; 4 | vector> stk; 5 | 6 | int is_cut[MAXN]; // v is cut vertex if is_cut[v] > 0 7 | vector bridge; // list of edge ids 8 | vector bcc_idx[MAXN]; // list of bccids for vertex i 9 | int bcc_cnt; 10 | 11 | void dfs(int nod, int par_edge) { 12 | up[nod] = visit[nod] = ++vtime; 13 | int child = 0; 14 | for (const auto& e : graph[nod]) { 15 | int next = e.first, edge_id = e.second; 16 | if (edge_id == par_edge) continue; 17 | if (visit[next] == 0) { 18 | stk.push_back({ nod, next }); 19 | ++child; 20 | dfs(next, edge_id); 21 | if (up[next] == visit[next]) bridge.push_back(edge_id); 22 | if (up[next] >= visit[nod]) { 23 | ++bcc_cnt; 24 | do { 25 | auto last = stk.back(); 26 | stk.pop_back(); 27 | bcc_idx[last.second].push_back(bcc_cnt); 28 | if (last == pair{ nod, next }) break; 29 | } while (!stk.empty()); 30 | bcc_idx[nod].push_back(bcc_cnt); 31 | is_cut[nod]++; 32 | } 33 | up[nod] = min(up[nod], up[next]); 34 | } 35 | else 36 | up[nod] = min(up[nod], visit[next]); 37 | } 38 | if (par_edge == -1 && is_cut[nod] == 1) 39 | is_cut[nod] = 0; 40 | } 41 | 42 | // find BCCs & cut vertexs & bridges in undirected graph 43 | // O(V+E) 44 | void get_bcc() { 45 | vtime = 0; 46 | memset(visit, 0, sizeof(visit)); 47 | memset(is_cut, 0, sizeof(is_cut)); 48 | bridge.clear(); 49 | for (int i = 0; i < n; ++i) bcc_idx[i].clear(); 50 | bcc_cnt = 0; 51 | for (int i = 0; i < n; ++i) { 52 | if (visit[i] == 0) 53 | dfs(i, -1); 54 | } 55 | } -------------------------------------------------------------------------------- /c++/math/ntt.cpp: -------------------------------------------------------------------------------- 1 | struct ntfft { 2 | // 7 * 2^26 + 1 3 | static const int ourmod = 469762049; 4 | static const int default_prim = 3; 5 | int n, w; 6 | ntfft(int _n) { 7 | --_n; 8 | for (int i = 1; i < 32 && (_n & (_n+1)); i += i) _n = (_n | (_n>>i)); 9 | n = ++_n; 10 | // default_prim^(7*2^26) = 1 11 | // (default_prim^(7*2^26/n))^n = 1 12 | int powcnt = (7<<26) / n; 13 | w = 1; 14 | for (long long curp = default_prim; powcnt; ) { 15 | if (powcnt & 1) w = w*curp%ourmod; 16 | powcnt >>= 1; 17 | curp = curp*curp%ourmod; 18 | } 19 | } 20 | void fft(int *p, const int n, const int s, int *res, const int w) { 21 | if (n == 4) { 22 | auto A = (p[0] + p[s*2]); 23 | auto B = (p[0] - p[s*2]); 24 | auto C = (p[s] + p[s*3]); 25 | auto D = (p[s] - p[s*3]); 26 | res[2] = (A-C)%ourmod; 27 | res[0] = (A+C)%ourmod; 28 | res[3] = (B - (long long)w*D)%ourmod; 29 | res[1] = (B + (long long)w*D)%ourmod; 30 | return; 31 | } 32 | if (n == 2) { 33 | res[0] = (p[0] + p[s]) % ourmod; 34 | res[1] = (p[0] - p[s]) % ourmod; 35 | return; 36 | } 37 | if (n == 1) { *res = *p; return; } 38 | fft(p, n>>1, s*2, res, w*(long long)w % ourmod); 39 | fft(p+s, n>>1, s*2, res + (n>>1), w*(long long)w % ourmod); 40 | long long w_power = 1; 41 | for (int i = 0; i < (n>>1); i++) { 42 | auto ofs = w_power * res[i+(n>>1)]; 43 | res[i+(n>>1)] = (res[i] - ofs) % ourmod; 44 | res[i] = (res[i] + ofs) % ourmod; 45 | w_power = (w_power * w) % ourmod; 46 | } 47 | } 48 | vector fft(vector &p) { 49 | vector res(n); 50 | p.resize(n); 51 | fft(p.data(), n, 1, res.data(),w); 52 | return res; 53 | } 54 | vector ifft(vector &p) { 55 | vector res(n); 56 | p.resize(n); 57 | fft(p.data(), n, 1, res.data(), modinverse(w, ourmod)); 58 | long long in = modinverse(n, ourmod); 59 | for (auto &v : res) { 60 | v = v * in % ourmod + ourmod; 61 | if (v >= ourmod) v -= ourmod; 62 | } 63 | return res; 64 | } 65 | }; -------------------------------------------------------------------------------- /rust/geometry/polygon.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::iter_ext::cur_next::cur_next; 2 | use crate::geometry::point::Point; 3 | use crate::numbers::num_traits::field::Field; 4 | use crate::numbers::num_traits::ring::Ring; 5 | 6 | pub struct Polygon { 7 | pub points: Vec>, 8 | } 9 | 10 | impl Polygon { 11 | pub fn new(points: Vec>) -> Self { 12 | Self { points } 13 | } 14 | } 15 | 16 | impl Polygon { 17 | pub fn area(&self) -> T { 18 | let mut ans = T::zero(); 19 | for (i, j) in cur_next(self.points.len()) { 20 | ans += self.points[i].x * self.points[j].y; 21 | ans -= self.points[i].y * self.points[j].x; 22 | } 23 | ans / (T::one() + T::one()) 24 | } 25 | } 26 | 27 | pub trait ConvexHull { 28 | fn convex_hull(self) -> Polygon; 29 | } 30 | 31 | impl ConvexHull for &mut [Point] { 32 | fn convex_hull(self) -> Polygon { 33 | self.sort_by(|a, b| a.partial_cmp(b).unwrap()); 34 | let p1 = self[0]; 35 | let pn = *self.last().unwrap(); 36 | let mut up = vec![p1]; 37 | let mut down = vec![p1]; 38 | for &p in self.iter().skip(1) { 39 | if p == pn || p1.line(pn).value(p) > T::zero() { 40 | while up.len() >= 2 && up[up.len() - 2].line(up[up.len() - 1]).value(p) <= T::zero() 41 | { 42 | up.pop(); 43 | } 44 | up.push(p); 45 | } 46 | if p == pn || p1.line(pn).value(p) < T::zero() { 47 | while down.len() >= 2 48 | && down[down.len() - 2].line(down[down.len() - 1]).value(p) >= T::zero() 49 | { 50 | down.pop(); 51 | } 52 | down.push(p); 53 | } 54 | } 55 | let mut ans = up; 56 | ans.extend(down.into_iter().skip(1).rev().skip(1)); 57 | Polygon::new(ans) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /rust/graph/edge_distances.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::iter_ext::min_max::IterMinMaxPos; 2 | use crate::graph::edges::edge_trait::{BidirectionalEdgeTrait, EdgeTrait}; 3 | use crate::graph::graph::Graph; 4 | use std::collections::VecDeque; 5 | 6 | pub trait EdgeAlgos { 7 | fn edge_distances(&self, source: usize) -> Vec; 8 | } 9 | 10 | pub trait BiEdgeAlgos: EdgeAlgos { 11 | fn centers(&self) -> Vec; 12 | } 13 | 14 | impl EdgeAlgos for Graph { 15 | fn edge_distances(&self, source: usize) -> Vec { 16 | // 1.43 17 | let mut dist = vec![std::u32::MAX; self.vertex_count()]; 18 | dist[source] = 0; 19 | let mut q = VecDeque::new(); 20 | q.push_back(source); 21 | while !q.is_empty() { 22 | let cur = q.pop_front().unwrap(); 23 | for e in self[cur].iter() { 24 | let next = e.to(); 25 | // 1.43 26 | if dist[next] == std::u32::MAX { 27 | dist[next] = dist[cur] + 1; 28 | q.push_back(next); 29 | } 30 | } 31 | } 32 | dist 33 | } 34 | } 35 | 36 | impl BiEdgeAlgos for Graph { 37 | fn centers(&self) -> Vec { 38 | debug_assert!(self.is_tree()); 39 | if self.vertex_count() == 0 { 40 | return Vec::new(); 41 | } 42 | let d0 = self.edge_distances(0); 43 | let first = d0.iter().max_position().unwrap(); 44 | let d1 = self.edge_distances(first); 45 | let second = d1.iter().max_position().unwrap(); 46 | let d2 = self.edge_distances(second); 47 | let mut res = Vec::new(); 48 | let r1 = d1[second] / 2; 49 | let r2 = (d1[second] + 1) / 2; 50 | for (i, (d1, d2)) in d1.iter().zip(d2.iter()).enumerate() { 51 | if *d1 == r1 && *d2 == r2 || *d1 == r2 && *d2 == r1 { 52 | res.push(i); 53 | } 54 | } 55 | res 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /rust/geometry/ray.rs: -------------------------------------------------------------------------------- 1 | use crate::geometry::line::Line; 2 | use crate::geometry::point::Point; 3 | use crate::numbers::num_traits::field::Field; 4 | use crate::numbers::num_traits::real::RealTrait; 5 | use crate::numbers::num_traits::ring::Ring; 6 | 7 | pub struct Ray { 8 | pub origin: Point, 9 | pub direction: Point, 10 | } 11 | 12 | impl Ray { 13 | pub fn new(origin: Point, direction: Point) -> Self { 14 | Self { origin, direction } 15 | } 16 | } 17 | 18 | impl Ray { 19 | pub fn line(&self) -> Line { 20 | self.origin.line(self.direction) 21 | } 22 | } 23 | 24 | impl Ray { 25 | pub fn contains(&self, p: Point) -> bool { 26 | if p == self.origin { 27 | return true; 28 | } 29 | let line = self.line(); 30 | if !line.contains(p) { 31 | return false; 32 | } 33 | if self.direction.x != self.origin.x 34 | && (p.x > self.origin.x) != (self.direction.x > self.origin.x) 35 | { 36 | return false; 37 | } 38 | if self.direction.y != self.origin.y 39 | && (p.y > self.origin.y) != (self.direction.y > self.origin.y) 40 | { 41 | return false; 42 | } 43 | true 44 | } 45 | 46 | pub fn square_dist_point(&self, p: Point) -> T { 47 | let line = self.line(); 48 | let perp = line.perpendicular(p); 49 | let pp = line.intersect(perp); 50 | if self.contains(pp) { 51 | pp.square_dist_point(p) 52 | } else { 53 | self.origin.square_dist_point(p) 54 | } 55 | } 56 | } 57 | 58 | impl Ray { 59 | pub fn angle(&self) -> T { 60 | (self.direction - self.origin).angle() 61 | } 62 | 63 | pub fn from_angle(origin: Point, angle: T) -> Self { 64 | Self::new(origin, origin + Point::from_polar(T::one(), angle)) 65 | } 66 | 67 | pub fn dist_point(&self, p: Point) -> T { 68 | self.square_dist_point(p).sqrt() 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /c++/string/suffix_array.cpp: -------------------------------------------------------------------------------- 1 | const int MAXN = 500005; 2 | struct SuffixArray { 3 | /* 4 | m : number of alphabet, n : string length 5 | sa[] : 0 ~ n-1(th) suffix sorting number (starting from 1) 6 | h[] : adjenct sa's lcp(starting from 2) 7 | rank[] : 0~n-1(th) suffix's rank (starting from 0) 8 | ex) banana 9 | *suffix number 10 | banana 0 11 | anana 1 12 | nana 2 13 | ana 3 14 | na 4 15 | a 5 16 | *rank[] 17 | banana 3 18 | anana 2 19 | nana 5 20 | ana 1 21 | na 4 22 | a 0 23 | *sa[] 24 | a 5 25 | ana 3 26 | anana 1 27 | banana 0 28 | na 4 29 | nana 2 30 | */ 31 | int n, m, i, j, k, r[MAXN], sa[MAXN], rank[MAXN], h[MAXN], A[MAXN], B[MAXN], V[MAXN], S[MAXN], T; 32 | void read(char* S) { 33 | m = 27; 34 | for (i = 0; S[i]; i++) r[i] = S[i]-'a'+1; 35 | n = i; 36 | } 37 | inline bool cmp(int a, int b, int l) { return B[a] == B[b] && B[a+l] == B[b+l]; } 38 | void calcSuffixArray(int n) { 39 | int p; 40 | for (i = 0; i < m; i++) S[i] = 0; 41 | for (i = 0; i < n; i++) S[A[i] = r[i]]++; 42 | for (i = 1; i < m; i++) S[i]+=S[i-1]; 43 | for (i = n-1; i >= 0; i--) sa[--S[A[i]]] = i; 44 | for (j = 1, p = 1; p= j) B[p++] = sa[i]-j; 47 | for (i = 0; i < m; i++) S[i] = 0; 48 | for (i = 0; i < n; i++) S[V[i] = A[B[i]]]++; 49 | for (i = 1; i < m; i++) S[i]+=S[i-1]; 50 | for (i = n-1; i >= 0; i--) sa[--S[V[i]]] = B[i]; 51 | for (i = 0; i < n; i++) T=A[i],A[i]=B[i],B[i]=T; 52 | p = 1, A[sa[0]] = 0; 53 | for (i = 1; i < n; i++) A[sa[i]] = cmp(sa[i-1], sa[i], j) ? p-1 : p++; 54 | } 55 | } 56 | void calcLCP() { 57 | k = 0; 58 | for (i = 1; i <= n; i++) rank[sa[i]] = i; 59 | for (i = 0; i < n; h[rank[i++]] = k) for (k?k--:0, j = sa[rank[i]-1]; r[i+k] == r[j+k]; k++); 60 | } 61 | void solve() { 62 | calcSuffixArray(n+1); 63 | calcLCP(); 64 | for (i = 1; i <= n; i++) printf("%d ",sa[i]); 65 | printf("\nx "); 66 | for (i = 2; i <= n; i++) printf("%d ",h[i]); 67 | } 68 | } A; 69 | int main() { 70 | char S[MAXN]; 71 | fgets(S, MAXN, stdin); 72 | A.read(S); A.solve(); 73 | } -------------------------------------------------------------------------------- /rust/graph/hl_decomposition.rs: -------------------------------------------------------------------------------- 1 | use crate::graph::edges::edge_trait::BidirectionalEdgeTrait; 2 | use crate::graph::graph::Graph; 3 | use crate::misc::recursive_function::{Callable2, RecursiveFunction2}; 4 | 5 | pub trait HLDecomposition { 6 | fn hl_decomposition_with_root(&self, root: usize) -> (Vec>, Vec, Vec); 7 | 8 | fn hl_decomposition(&self) -> (Vec>, Vec, Vec) { 9 | self.hl_decomposition_with_root(0) 10 | } 11 | } 12 | impl HLDecomposition for Graph { 13 | fn hl_decomposition_with_root(&self, root: usize) -> (Vec>, Vec, Vec) { 14 | debug_assert!(self.is_tree()); 15 | let n = self.vertex_count(); 16 | let mut paths = Vec::new(); 17 | let mut id = vec![0; n]; 18 | let mut pos = vec![0; n]; 19 | let mut size = vec![0u32; n]; 20 | let mut calc_size = RecursiveFunction2::new(|f, vert, last| { 21 | size[vert] = 1; 22 | for e in self[vert].iter() { 23 | let next = e.to(); 24 | if next == last { 25 | continue; 26 | } 27 | size[vert] += f.call(next, vert); 28 | } 29 | size[vert] 30 | }); 31 | calc_size.call(root, root); 32 | paths.push(vec![root]); 33 | let mut build = RecursiveFunction2::new(|f, vert: usize, last| { 34 | if vert != root { 35 | if 2 * size[vert] >= size[last] { 36 | id[vert] = id[last]; 37 | pos[vert] = pos[last] + 1; 38 | paths[id[vert]].push(vert); 39 | } else { 40 | id[vert] = paths.len(); 41 | paths.push(vec![vert]); 42 | } 43 | } 44 | for e in self[vert].iter() { 45 | let next = e.to(); 46 | if next == last { 47 | continue; 48 | } 49 | f.call(next, vert); 50 | } 51 | }); 52 | build.call(root, root); 53 | (paths, id, pos) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /rust/numbers/inf_int.rs: -------------------------------------------------------------------------------- 1 | use crate::io::output::{Output, Writable}; 2 | use crate::misc::value::Value; 3 | use crate::numbers::num_traits::add_sub::AddSub; 4 | use crate::numbers::num_traits::mul_div_rem::MulDiv; 5 | use crate::numbers::num_traits::zero_one::ZeroOne; 6 | use std::marker::PhantomData; 7 | use std::ops::{Add, AddAssign, Mul, MulAssign}; 8 | 9 | #[derive(Ord, PartialOrd, Eq, PartialEq, Copy, Clone)] 10 | pub struct InfInt> { 11 | n: T, 12 | phantom: PhantomData, 13 | } 14 | 15 | impl> InfInt { 16 | pub fn new(n: T) -> Self { 17 | Self { 18 | n: n.min(V::val()), 19 | phantom: Default::default(), 20 | } 21 | } 22 | 23 | pub fn is_infinity(&self) -> bool { 24 | self.n == V::val() 25 | } 26 | } 27 | 28 | impl> AddAssign for InfInt { 29 | fn add_assign(&mut self, rhs: Self) { 30 | if rhs.is_infinity() || V::val() - rhs.n <= self.n { 31 | self.n = V::val(); 32 | } else { 33 | self.n += rhs.n; 34 | } 35 | } 36 | } 37 | 38 | impl> Add for InfInt { 39 | type Output = Self; 40 | 41 | fn add(mut self, rhs: Self) -> Self::Output { 42 | self += rhs; 43 | self 44 | } 45 | } 46 | 47 | impl> MulAssign for InfInt { 48 | fn mul_assign(&mut self, rhs: Self) { 49 | if rhs.n != T::zero() && V::val() / rhs.n < self.n { 50 | self.n = V::val(); 51 | } else { 52 | self.n *= rhs.n; 53 | } 54 | } 55 | } 56 | 57 | impl> Mul for InfInt { 58 | type Output = Self; 59 | 60 | fn mul(mut self, rhs: Self) -> Self::Output { 61 | self *= rhs; 62 | self 63 | } 64 | } 65 | 66 | impl> Writable for InfInt { 67 | fn write(&self, output: &mut Output) { 68 | self.n.write(output) 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /rust/numbers/test.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::primes::factorize::Factorize; 2 | 3 | mod mod_int { 4 | use crate::numbers::mod_int::ModInt7; 5 | use crate::numbers::num_traits::zero_one::ZeroOne; 6 | 7 | type Mod = ModInt7; 8 | 9 | #[test] 10 | fn add() { 11 | let x = Mod::new(1); 12 | let y = Mod::new(2); 13 | assert_eq!(format!("{}", x + y), "3"); 14 | } 15 | 16 | #[test] 17 | fn sub() { 18 | let x = Mod::new(1); 19 | let y = Mod::new(2); 20 | assert_eq!(format!("{}", x - y), "1000000006"); 21 | assert_eq!(format!("{:?}", x - y), "-1"); 22 | } 23 | 24 | #[test] 25 | fn mul() { 26 | let x = Mod::new(3); 27 | let y = Mod::new(5); 28 | assert_eq!(format!("{}", x * y), "15"); 29 | } 30 | 31 | #[test] 32 | fn div() { 33 | let x = Mod::new(3); 34 | let y = Mod::new(5); 35 | assert_eq!(format!("{}", x / y), "200000002"); 36 | assert_eq!(format!("{:?}", x / y), "3/5"); 37 | } 38 | 39 | #[test] 40 | fn div_assign() { 41 | let mut x = Mod::new(3); 42 | let y = Mod::new(5); 43 | x /= y; 44 | assert_eq!(format!("{}", x), "200000002"); 45 | assert_eq!(format!("{:?}", x), "3/5"); 46 | } 47 | 48 | #[test] 49 | fn dbg_format() { 50 | let x = Mod::new(1) / Mod::new(2); 51 | let y = Mod::new(1) / Mod::new(3); 52 | assert_eq!(format!("{}", x + y), "833333340"); 53 | assert_eq!(format!("{:?}", x + y), "5/6"); 54 | } 55 | 56 | #[test] 57 | fn dbg_format_big() { 58 | let x = Mod::new(123) / Mod::new(457); 59 | assert_eq!(format!("{:?}", x), "(?? 262582059 ??)"); 60 | } 61 | 62 | #[test] 63 | fn dbg_format_more() { 64 | assert_eq!(format!("{:?}", Mod::new(1)), "1"); 65 | assert_eq!(format!("{:?}", Mod::new(3)), "3"); 66 | assert_eq!(format!("{:?}", Mod::new(-5)), "-5"); 67 | } 68 | 69 | #[test] 70 | fn consts() { 71 | let one = Mod::one() - Mod::zero(); 72 | assert_eq!(format!("{:?}", one), "1"); 73 | } 74 | } 75 | 76 | #[test] 77 | fn test_divisors() { 78 | for i in 1..100000 { 79 | i.prime_divisors(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /rust/graph/edges/bi_edge.rs: -------------------------------------------------------------------------------- 1 | use crate::graph::edges::bi_edge_trait::BiEdgeTrait; 2 | use crate::graph::edges::edge_id::{EdgeId, NoId, WithId}; 3 | use crate::graph::edges::edge_trait::{BidirectionalEdgeTrait, EdgeTrait}; 4 | use crate::graph::graph::Graph; 5 | use crate::io::input::{Input, Readable}; 6 | 7 | #[derive(Clone)] 8 | pub struct BiEdgeRaw { 9 | to: u32, 10 | id: Id, 11 | } 12 | 13 | impl BiEdgeRaw { 14 | pub fn new(to: usize) -> Self { 15 | Self { 16 | to: to as u32, 17 | id: Id::new(), 18 | } 19 | } 20 | } 21 | 22 | impl BidirectionalEdgeTrait for BiEdgeRaw {} 23 | 24 | impl EdgeTrait for BiEdgeRaw { 25 | const REVERSABLE: bool = true; 26 | 27 | fn to(&self) -> usize { 28 | self.to as usize 29 | } 30 | 31 | fn id(&self) -> usize { 32 | self.id.id() 33 | } 34 | 35 | fn set_id(&mut self, id: usize) { 36 | self.id.set_id(id); 37 | } 38 | 39 | fn reverse_id(&self) -> usize { 40 | panic!("no reverse id") 41 | } 42 | 43 | fn set_reverse_id(&mut self, _: usize) {} 44 | 45 | fn reverse_edge(&self, from: usize) -> Self { 46 | Self::new(from) 47 | } 48 | } 49 | 50 | impl BiEdgeTrait for BiEdgeRaw {} 51 | 52 | pub type BiEdge = BiEdgeRaw; 53 | pub type BiEdgeWithId = BiEdgeRaw; 54 | 55 | pub trait ReadBiEdgeGraph { 56 | fn read_graph(&mut self, n: usize, m: usize) -> Graph>; 57 | 58 | fn read_tree(&mut self, n: usize) -> Graph> { 59 | self.read_graph(n, n - 1) 60 | } 61 | } 62 | 63 | impl ReadBiEdgeGraph for Input<'_> { 64 | fn read_graph(&mut self, n: usize, m: usize) -> Graph> { 65 | let mut graph = Graph::new(n); 66 | for _ in 0..m { 67 | graph.add_edge(self.read(), BiEdgeRaw::new(self.read())); 68 | } 69 | graph 70 | } 71 | } 72 | 73 | impl Readable for Graph> { 74 | fn read(input: &mut Input) -> Self { 75 | let n = input.read(); 76 | let m = input.read(); 77 | ::read_graph(input, n, m) 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /c++/graph/MaximumFlow_Dinic.cpp: -------------------------------------------------------------------------------- 1 | // usage: 2 | // MaxFlowDinic::init(n); 3 | // MaxFlowDinic::add_edge(0, 1, 100, 100); // for bidirectional edge 4 | // MaxFlowDinic::add_edge(1, 2, 100); // directional edge 5 | // result = MaxFlowDinic::solve(0, 2); // source -> sink 6 | // G[i][edgeIndex].res -> residual 7 | // 8 | // in order to find out the minimum cut, use `l'. 9 | // if l[i] == 0, i is unrechable. 10 | // 11 | // O(V*V*E) 12 | // with unit capacities, O(min(V^(2/3), E^(1/2)) * E) 13 | struct MaxFlowDinic { 14 | typedef int flow_t; 15 | struct Edge { 16 | int next; 17 | size_t inv; /* inverse edge index */ 18 | flow_t res; /* residual */ 19 | }; 20 | int n; 21 | vector> G; 22 | vector q, l, start; 23 | 24 | void init(int _n) { 25 | n = _n; 26 | G.resize(n); 27 | for (int i = 0; i < n; i++) G[i].clear(); 28 | } 29 | void add_edge(int s, int e, flow_t cap, flow_t caprev = 0) { 30 | Edge forward{ e, G[e].size(), cap }; 31 | Edge reverse{ s, G[s].size(), caprev }; 32 | G[s].push_back(forward); 33 | G[e].push_back(reverse); 34 | } 35 | bool assign_level(int source, int sink) { 36 | int t = 0; 37 | memset(&l[0], 0, sizeof(l[0]) * l.size()); 38 | l[source] = 1; 39 | q[t++] = source; 40 | for (int h = 0; h < t && !l[sink]; h++) { 41 | int cur = q[h]; 42 | for (const auto& e : G[cur]) { 43 | if (l[e.next] || e.res == 0) continue; 44 | l[e.next] = l[cur] + 1; 45 | q[t++] = e.next; 46 | } 47 | } 48 | return l[sink] != 0; 49 | } 50 | flow_t block_flow(int cur, int sink, flow_t current) { 51 | if (cur == sink) return current; 52 | for (int& i = start[cur]; i < G[cur].size(); i++) { 53 | auto& e = G[cur][i]; 54 | if (e.res == 0 || l[e.next] != l[cur] + 1) continue; 55 | if (flow_t res = block_flow(e.next, sink, min(e.res, current))) { 56 | e.res -= res; 57 | G[e.next][e.inv].res += res; 58 | return res; 59 | } 60 | } 61 | return 0; 62 | } 63 | flow_t solve(int source, int sink) { 64 | q.resize(n); 65 | l.resize(n); 66 | start.resize(n); 67 | flow_t ans = 0; 68 | while (assign_level(source, sink)) { 69 | memset(&start[0], 0, sizeof(start[0]) * n); 70 | while (flow_t flow = block_flow(source, sink, numeric_limits::max())) 71 | ans += flow; 72 | } 73 | return ans; 74 | } 75 | }; -------------------------------------------------------------------------------- /rust/collections/fenwick.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::legacy_fill::LegacyFill; 2 | use crate::collections::min_max::MinimMaxim; 3 | use crate::numbers::num_traits::add_sub::AddSub; 4 | use crate::numbers::num_traits::zero_one::ZeroOne; 5 | use std::ops::RangeBounds; 6 | 7 | #[derive(Clone)] 8 | pub struct FenwickTree { 9 | value: Vec, 10 | } 11 | 12 | impl FenwickTree { 13 | pub fn new(size: usize) -> Self { 14 | Self { 15 | value: vec![T::zero(); size], 16 | } 17 | } 18 | 19 | pub fn get_to(&self, mut to: usize) -> T { 20 | to.minim(self.value.len()); 21 | let mut result = T::zero(); 22 | while to > 0 { 23 | to -= 1; 24 | result += self.value[to]; 25 | to &= to + 1; 26 | } 27 | result 28 | } 29 | 30 | pub fn get(&self, bounds: impl RangeBounds) -> T { 31 | let from = match bounds.start_bound() { 32 | std::ops::Bound::Included(&x) => x, 33 | std::ops::Bound::Excluded(&x) => x + 1, 34 | std::ops::Bound::Unbounded => 0, 35 | }; 36 | let to = match bounds.end_bound() { 37 | std::ops::Bound::Included(&x) => x + 1, 38 | std::ops::Bound::Excluded(&x) => x, 39 | std::ops::Bound::Unbounded => self.value.len(), 40 | }; 41 | if from >= to { 42 | T::zero() 43 | } else { 44 | self.get_to(to) - self.get_to(from) 45 | } 46 | } 47 | 48 | pub fn add(&mut self, mut at: usize, v: T) { 49 | while at < self.value.len() { 50 | self.value[at] += v; 51 | at |= at + 1; 52 | } 53 | } 54 | 55 | pub fn iter(&self) -> impl Iterator + '_ { 56 | self.value 57 | .iter() 58 | .enumerate() 59 | // edition 2021 60 | .map(move |(i, _)| self.get(i..=i)) 61 | } 62 | 63 | pub fn clear(&mut self) { 64 | self.value.legacy_fill(T::zero()); 65 | } 66 | } 67 | 68 | impl From<&[T]> for FenwickTree { 69 | fn from(slice: &[T]) -> Self { 70 | let mut result = Self::new(slice.len()); 71 | for (i, &v) in slice.iter().enumerate() { 72 | result.add(i, v); 73 | } 74 | result 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /rust/collections/dsu.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::iter_ext::collect::IterCollect; 2 | use crate::collections::legacy_fill::LegacyFill; 3 | use crate::collections::slice_ext::bounds::Bounds; 4 | use std::cell::Cell; 5 | 6 | #[derive(Clone)] 7 | pub struct DSU { 8 | id: Vec>, 9 | size: Vec, 10 | count: usize, 11 | } 12 | 13 | impl DSU { 14 | pub fn new(n: usize) -> Self { 15 | Self { 16 | id: (0..n).map(|i| Cell::new(i as u32)).collect_vec(), 17 | size: vec![1; n], 18 | count: n, 19 | } 20 | } 21 | 22 | pub fn size(&self, i: usize) -> usize { 23 | self.size[self.get(i)] as usize 24 | } 25 | 26 | #[allow(clippy::len_without_is_empty)] 27 | pub fn len(&self) -> usize { 28 | self.id.len() 29 | } 30 | 31 | pub fn iter(&self) -> impl Iterator + '_ { 32 | self.id.iter().enumerate().filter_map(|(i, id)| { 33 | if (i as u32) == id.get() { 34 | Some(i) 35 | } else { 36 | None 37 | } 38 | }) 39 | } 40 | 41 | pub fn set_count(&self) -> usize { 42 | self.count 43 | } 44 | 45 | pub fn join(&mut self, mut a: usize, mut b: usize) -> bool { 46 | a = self.get(a); 47 | b = self.get(b); 48 | if a == b { 49 | false 50 | } else { 51 | self.size[a] += self.size[b]; 52 | self.id[b].replace(a as u32); 53 | self.count -= 1; 54 | true 55 | } 56 | } 57 | 58 | pub fn get(&self, i: usize) -> usize { 59 | if self.id[i].get() != i as u32 { 60 | let res = self.get(self.id[i].get() as usize); 61 | self.id[i].replace(res as u32); 62 | } 63 | self.id[i].get() as usize 64 | } 65 | 66 | pub fn clear(&mut self) { 67 | self.count = self.id.len(); 68 | self.size.legacy_fill(1); 69 | self.id.iter().enumerate().for_each(|(i, id)| { 70 | id.replace(i as u32); 71 | }); 72 | } 73 | 74 | pub fn parts(&self) -> Vec> { 75 | let roots = self.iter().collect_vec(); 76 | let mut res = vec![Vec::new(); roots.len()]; 77 | for i in 0..self.id.len() { 78 | res[roots.as_slice().bin_search(&self.get(i)).unwrap()].push(i); 79 | } 80 | res 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /c++/miscellaneous/fastio.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /** Interface */ 4 | 5 | inline int readChar(); 6 | template inline T readInt(); 7 | template inline void writeInt( T x, char end = 0 ); 8 | inline void writeChar( int x ); 9 | inline void writeWord( const char *s ); 10 | 11 | /** Read */ 12 | 13 | static const int buf_size = 4096; 14 | 15 | inline int getChar() { 16 | static char buf[buf_size]; 17 | static int len = 0, pos = 0; 18 | if (pos == len) 19 | pos = 0, len = fread(buf, 1, buf_size, stdin); 20 | if (pos == len) 21 | return -1; 22 | return buf[pos++]; 23 | } 24 | 25 | inline int readChar() { 26 | int c = getChar(); 27 | while (c <= 32) 28 | c = getChar(); 29 | return c; 30 | } 31 | 32 | template 33 | inline T readInt() { 34 | int s = 1, c = readChar(); 35 | T x = 0; 36 | if (c == '-') 37 | s = -1, c = getChar(); 38 | while ('0' <= c && c <= '9') 39 | x = x * 10 + c - '0', c = getChar(); 40 | return s == 1 ? x : -x; 41 | } 42 | 43 | /** Write */ 44 | 45 | static int write_pos = 0; 46 | static char write_buf[buf_size]; 47 | 48 | inline void writeChar( int x ) { 49 | if (write_pos == buf_size) 50 | fwrite(write_buf, 1, buf_size, stdout), write_pos = 0; 51 | write_buf[write_pos++] = x; 52 | } 53 | 54 | template 55 | inline void writeInt( T x, char end ) { 56 | if (x < 0) 57 | writeChar('-'), x = -x; 58 | 59 | char s[24]; 60 | int n = 0; 61 | while (x || !n) 62 | s[n++] = '0' + x % 10, x /= 10; 63 | while (n--) 64 | writeChar(s[n]); 65 | if (end) 66 | writeChar(end); 67 | } 68 | 69 | inline void writeWord( const char *s ) { 70 | while (*s) 71 | writeChar(*s++); 72 | } 73 | 74 | struct Flusher { 75 | ~Flusher() { 76 | if (write_pos) 77 | fwrite(write_buf, 1, write_pos, stdout), write_pos = 0; 78 | } 79 | } flusher; 80 | 81 | /** Example */ 82 | 83 | #include 84 | 85 | int main() { 86 | /** If you need some files */ 87 | assert(freopen("input.txt", "r", stdin)); 88 | assert(freopen("output.txt", "w", stdout)); 89 | 90 | int a = readInt(); 91 | int b = readInt(); 92 | writeInt(a + b); 93 | writeChar('\n'); 94 | // writeInt(a + b, '\n'); 95 | } 96 | 97 | /** 98 | Common troubles: 99 | 1. Вводите данные в среде, не вводится... Ввод буферизованный, он ждет конца ввода. Нажмите Ctrl+D или Ctrl+Z. 100 | */ 101 | -------------------------------------------------------------------------------- /rust/collections/divided_set.rs: -------------------------------------------------------------------------------- 1 | use crate::misc::direction::Direction; 2 | use std::collections::BTreeSet; 3 | 4 | pub struct DividedSet<'s, T: Ord> { 5 | left: BTreeSet, 6 | right: BTreeSet, 7 | criteria: Box Option + 's>, 8 | } 9 | 10 | impl<'s, T: Ord + Clone> DividedSet<'s, T> { 11 | pub fn new(criteria: impl Fn(usize, usize) -> Option + 's) -> Self { 12 | Self { 13 | left: BTreeSet::new(), 14 | right: BTreeSet::new(), 15 | criteria: Box::new(criteria), 16 | } 17 | } 18 | 19 | pub fn left_tail(&self) -> Option<&T> { 20 | self.left.iter().next_back() 21 | } 22 | 23 | pub fn right_head(&self) -> Option<&T> { 24 | self.right.iter().next() 25 | } 26 | 27 | pub fn insert(&mut self, value: T) -> bool { 28 | let res = if let Some(left_tail) = self.left_tail() { 29 | if value < *left_tail { 30 | self.left.insert(value) 31 | } else { 32 | self.right.insert(value) 33 | } 34 | } else if let Some(right_head) = self.right_head() { 35 | if value < *right_head { 36 | self.left.insert(value) 37 | } else { 38 | self.right.insert(value) 39 | } 40 | } else { 41 | self.left.insert(value) 42 | }; 43 | if res { 44 | self.balance(); 45 | } 46 | res 47 | } 48 | 49 | pub fn remove(&mut self, value: &T) -> bool { 50 | let res = self.left.remove(value) || self.right.remove(value); 51 | if res { 52 | self.balance(); 53 | } 54 | res 55 | } 56 | 57 | fn balance(&mut self) { 58 | while let Some(direction) = (self.criteria)(self.left.len(), self.right.len()) { 59 | match direction { 60 | Direction::Right => { 61 | let value = self.left.iter().next_back().unwrap().clone(); 62 | self.left.remove(&value); 63 | self.right.insert(value); 64 | } 65 | Direction::Left => { 66 | let value = self.right.iter().next().unwrap().clone(); 67 | self.right.remove(&value); 68 | self.left.insert(value); 69 | } 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /c++/graph/Edmonds Blossom by koosaga.cpp: -------------------------------------------------------------------------------- 1 | // Edmond's Blossom Algorithm 2 | // Computes maximum matchings for a general graph 3 | 4 | // usage: 5 | // GM G; 6 | // G.init(|V|) // G = (V, E) 7 | // for (each edges) G.add_edge(u, v); 8 | // G.Match(); // # of matched pairs 9 | // Time Complexity : O(|E|*|V|^2) 10 | // Space Complexity : O(|V|^2) 11 | #include 12 | using namespace std; 13 | 14 | const int MAXN = 2005; 15 | 16 | struct GM { // 1-based Vertex index 17 | int vis[MAXN], par[MAXN], orig[MAXN], match[MAXN], aux[MAXN], t, N; 18 | vector conn[MAXN]; 19 | queue Q; 20 | void addEdge(int u, int v) { 21 | conn[u].push_back(v); conn[v].push_back(u); 22 | } 23 | void init(int n) { 24 | N = n; t = 0; 25 | for(int i=0; i<=n; ++i) { 26 | conn[i].clear(); 27 | match[i] = aux[i] = par[i] = 0; 28 | } 29 | } 30 | void augment(int u, int v) { 31 | int pv = v, nv; 32 | do { 33 | pv = par[v]; nv = match[pv]; 34 | match[v] = pv; match[pv] = v; 35 | v = nv; 36 | } while(u != pv); 37 | } 38 | int lca(int v, int w) { 39 | ++t; 40 | while(true) { 41 | if(v) { 42 | if(aux[v] == t) return v; aux[v] = t; 43 | v = orig[par[match[v]]]; 44 | } 45 | swap(v, w); 46 | } 47 | } 48 | void blossom(int v, int w, int a) { 49 | while(orig[v] != a) { 50 | par[v] = w; w = match[v]; 51 | if(vis[w] == 1) Q.push(w), vis[w] = 0; 52 | orig[v] = orig[w] = a; 53 | v = par[w]; 54 | } 55 | } 56 | bool bfs(int u) { 57 | fill(vis+1, vis+1+N, -1); iota(orig + 1, orig + N + 1, 1); 58 | Q = queue (); Q.push(u); vis[u] = 0; 59 | while(!Q.empty()) { 60 | int v = Q.front(); Q.pop(); 61 | for(int x: conn[v]) { 62 | if(vis[x] == -1) { 63 | par[x] = v; vis[x] = 1; 64 | if(!match[x]) return augment(u, x), true; 65 | Q.push(match[x]); vis[match[x]] = 0; 66 | } 67 | else if(vis[x] == 0 && orig[v] != orig[x]) { 68 | int a = lca(orig[v], orig[x]); 69 | blossom(x, v, a); blossom(v, x, a); 70 | } 71 | } 72 | } 73 | return false; 74 | } 75 | int Match() { 76 | int ans = 0; 77 | //find random matching (not necessary, constant improvement) 78 | vector V(N-1); iota(V.begin(), V.end(), 1); 79 | shuffle(V.begin(), V.end(), mt19937(0x94949)); 80 | for(auto x: V) if(!match[x]){ 81 | for(auto y: conn[x]) if(!match[y]) { 82 | match[x] = y, match[y] = x; 83 | ++ans; break; 84 | } 85 | } 86 | for(int i=1; i<=N; ++i) if(!match[i] && bfs(i)) ++ans; 87 | return ans; 88 | } 89 | } -------------------------------------------------------------------------------- /rust/numbers/gauss.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::md_arr::arr2d::Arr2d; 2 | use crate::numbers::num_traits::add_sub::AddSub; 3 | use crate::numbers::num_traits::mul_div_rem::MulDiv; 4 | use crate::numbers::num_traits::zero_one::ZeroOne; 5 | 6 | pub fn gauss(mat: &mut Arr2d) { 7 | let mut skip = 0; 8 | for i in 0..mat.d2() { 9 | let mut good = false; 10 | for j in skip..mat.d1() { 11 | if mat[(j, i)] != T::zero() { 12 | good = true; 13 | for k in i..mat.d2() { 14 | mat.swap(j, k, skip, k); 15 | } 16 | break; 17 | } 18 | } 19 | if !good { 20 | continue; 21 | } 22 | for j in (i..mat.d2()).rev() { 23 | let v = mat[(skip, i)]; 24 | mat[(skip, j)] /= v; 25 | } 26 | for j in 0..mat.d1() { 27 | if j == skip { 28 | continue; 29 | } 30 | for k in (i..mat.d2()).rev() { 31 | let v = mat[(j, i)] * mat[(skip, k)]; 32 | mat[(j, k)] -= v; 33 | } 34 | } 35 | skip += 1; 36 | } 37 | } 38 | 39 | pub fn det(mat: &mut Arr2d) -> T { 40 | if mat.d1() != mat.d2() { 41 | return T::zero(); 42 | } 43 | let mut skip = 0; 44 | let mut ans = T::one(); 45 | let minus_one = T::zero() - T::one(); 46 | for i in 0..mat.d2() { 47 | let mut good = false; 48 | for j in skip..mat.d1() { 49 | if mat[(j, i)] != T::zero() { 50 | good = true; 51 | if skip != j { 52 | ans *= minus_one; 53 | for k in i..mat.d2() { 54 | mat.swap(j, k, skip, k); 55 | } 56 | } 57 | break; 58 | } 59 | } 60 | if !good { 61 | return T::zero(); 62 | } 63 | ans *= mat[(skip, i)]; 64 | for j in (i..mat.d2()).rev() { 65 | let v = mat[(skip, i)]; 66 | mat[(skip, j)] /= v; 67 | } 68 | for j in 0..mat.d1() { 69 | if j == skip { 70 | continue; 71 | } 72 | for k in (i..mat.d2()).rev() { 73 | let v = mat[(j, i)] * mat[(skip, k)]; 74 | mat[(j, k)] -= v; 75 | } 76 | } 77 | skip += 1; 78 | } 79 | ans 80 | } 81 | -------------------------------------------------------------------------------- /rust/misc/recursive_function.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | macro_rules! recursive_function { 4 | ($name: ident, $trait: ident, ($($type: ident $arg: ident,)*)) => { 5 | pub trait $trait<$($type, )*Output> { 6 | fn call(&mut self, $($arg: $type,)*) -> Output; 7 | } 8 | 9 | pub struct $name 10 | where 11 | F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output, 12 | { 13 | f: std::cell::UnsafeCell, 14 | $($arg: PhantomData<$type>, 15 | )* 16 | phantom_output: PhantomData, 17 | } 18 | 19 | impl $name 20 | where 21 | F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output, 22 | { 23 | pub fn new(f: F) -> Self { 24 | Self { 25 | f: std::cell::UnsafeCell::new(f), 26 | $($arg: Default::default(), 27 | )* 28 | phantom_output: Default::default(), 29 | } 30 | } 31 | } 32 | 33 | impl $trait<$($type, )*Output> for $name 34 | where 35 | F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output, 36 | { 37 | fn call(&mut self, $($arg: $type,)*) -> Output { 38 | unsafe { (*self.f.get())(self, $($arg, )*) } 39 | } 40 | } 41 | } 42 | } 43 | 44 | recursive_function!(RecursiveFunction0, Callable0, ()); 45 | recursive_function!(RecursiveFunction, Callable, (Arg arg,)); 46 | recursive_function!(RecursiveFunction2, Callable2, (Arg1 arg1, Arg2 arg2,)); 47 | recursive_function!(RecursiveFunction3, Callable3, (Arg1 arg1, Arg2 arg2, Arg3 arg3,)); 48 | recursive_function!(RecursiveFunction4, Callable4, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4,)); 49 | recursive_function!(RecursiveFunction5, Callable5, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5,)); 50 | recursive_function!(RecursiveFunction6, Callable6, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6,)); 51 | recursive_function!(RecursiveFunction7, Callable7, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7,)); 52 | recursive_function!(RecursiveFunction8, Callable8, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8,)); 53 | recursive_function!(RecursiveFunction9, Callable9, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9,)); 54 | -------------------------------------------------------------------------------- /c++/math/convex_hull.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef long long ll; 4 | 5 | const int SZ = 100005; 6 | 7 | template void myswap(T &a, T &b) { 8 | T tmp = a; a = b; b = tmp; 9 | } 10 | 11 | struct Point { 12 | int x, y; 13 | Point() {} 14 | Point(int x, int y) : x(x), y(y) {} 15 | }; 16 | 17 | class ConvexHull { 18 | public: 19 | int N; 20 | /* P : Given Points, H : Points making a convex hull */ 21 | Point P[SZ], tmp[SZ], H[SZ]; 22 | int st[SZ], top; 23 | void init(){ 24 | N = 0; 25 | } 26 | void add(int x, int y) { 27 | P[++N] = Point(x, y); 28 | } 29 | int dir(int i, int j, int k) { 30 | ll x1 = P[j].x - P[i].x, y1 = P[j].y - P[i].y; 31 | ll x2 = P[k].x - P[i].x, y2 = P[k].y - P[i].y; 32 | ll outer_product = x1*y2 - x2*y1; 33 | if (outer_product > 0) return 1; 34 | if (outer_product < 0) return -1; 35 | return 0; 36 | } 37 | ll dist(int i, int j) { 38 | ll dx = P[i].x - P[j].x, dy = P[i].y - P[j].y; 39 | return dx*dx + dy*dy; 40 | } 41 | bool cmp(int i, int j) { 42 | int t = dir(1, i, j); 43 | if (t > 0 || (t == 0 && dist(1, i) <= dist(1, j))) return 1; 44 | return 0; 45 | } 46 | void sort(int s, int e) { 47 | if (s < e) { 48 | int m = (s + e) / 2; 49 | sort(s, m); 50 | sort(m + 1, e); 51 | int p1 = s, p2 = m + 1, p3 = s; 52 | while (p1 <= m && p2 <= e) { 53 | if (cmp(p1, p2)) tmp[p3++] = P[p1++]; 54 | else tmp[p3++] = P[p2++]; 55 | } 56 | while (p1 <= m) tmp[p3++] = P[p1++]; 57 | while (p2 <= e) tmp[p3++] = P[p2++]; 58 | for (int i = s; i <= e; i++) P[i] = tmp[i]; 59 | } 60 | } 61 | void compute() { 62 | /* 63 | Step 1. Find the lowest, the most left side point 64 | Make the point as the first point with swapping 65 | */ 66 | int p = 1; 67 | for (int i = 2; i <= N; i++) { 68 | if (P[i].y < P[p].y || (P[i].y == P[p].y && P[i].x < P[p].x)) 69 | p = i; 70 | } 71 | myswap(P[1], P[p]); 72 | /* Step 2. Sorting */ 73 | sort(2, N); 74 | /* Step 3. Push & Pop */ 75 | st[top = 1] = 1; 76 | for (int i = 2; i <= N; i++) { 77 | if (top < 2) st[++top] = i; 78 | else { 79 | while (top >= 2 && dir(st[top - 1], st[top], i) <= 0) top--; 80 | st[++top] = i; 81 | } 82 | } 83 | for (int i = 1; i <= top; i++) H[i] = P[st[i]]; 84 | N = top; 85 | } 86 | }; 87 | 88 | ConvexHull C; 89 | 90 | int main(){ 91 | int T; for (scanf("%d", &T); T--;) { 92 | int n; 93 | scanf("%d", &n); 94 | C.init(); 95 | for (int i = 0; i < n; i++) { 96 | int x, y; scanf("%d%d", &x, &y); 97 | C.add(x, y); 98 | } 99 | C.compute(); 100 | static int tc = 0; 101 | printf("#%d %d\n", ++tc, C.N); 102 | } 103 | } -------------------------------------------------------------------------------- /rust/misc/random.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::slice_ext::indices::Indices; 2 | use std::time::SystemTime; 3 | 4 | const NN: usize = 312; 5 | const MM: usize = 156; 6 | const MATRIX_A: u64 = 0xB5026F5AA96619E9; 7 | const UM: u64 = 0xFFFFFFFF80000000; 8 | const LM: u64 = 0x7FFFFFFF; 9 | const F: u64 = 6364136223846793005; 10 | const MAG01: [u64; 2] = [0, MATRIX_A]; 11 | 12 | pub struct Random { 13 | mt: [u64; NN], 14 | index: usize, 15 | } 16 | 17 | impl Random { 18 | pub fn new(seed: u64) -> Self { 19 | let mut res = Self { 20 | mt: [0u64; NN], 21 | index: NN, 22 | }; 23 | res.mt[0] = seed; 24 | for i in 1..NN { 25 | res.mt[i] = F 26 | .wrapping_mul(res.mt[i - 1] ^ (res.mt[i - 1] >> 62)) 27 | .wrapping_add(i as u64); 28 | } 29 | res 30 | } 31 | 32 | pub fn gen(&mut self) -> u64 { 33 | if self.index == NN { 34 | for i in 0..(NN - MM) { 35 | let x = (self.mt[i] & UM) | (self.mt[i + 1] & LM); 36 | self.mt[i] = self.mt[i + MM] ^ (x >> 1) ^ MAG01[(x & 1) as usize]; 37 | } 38 | for i in (NN - MM)..(NN - 1) { 39 | let x = (self.mt[i] & UM) | (self.mt[i + 1] & LM); 40 | self.mt[i] = self.mt[i + MM - NN] ^ (x >> 1) ^ MAG01[(x & 1) as usize]; 41 | } 42 | let x = (self.mt[NN - 1] & UM) | (self.mt[0] & LM); 43 | self.mt[NN - 1] = self.mt[MM - 1] ^ (x >> 1) ^ MAG01[(x & 1) as usize]; 44 | self.index = 0; 45 | } 46 | let mut x = self.mt[self.index]; 47 | self.index += 1; 48 | x ^= (x >> 29) & 0x5555555555555555; 49 | x ^= (x << 17) & 0x71D67FFFEDA60000; 50 | x ^= (x << 37) & 0xFFF7EEE000000000; 51 | x ^= x >> 43; 52 | x 53 | } 54 | 55 | pub fn next(&mut self, n: u64) -> u64 { 56 | self.gen() % n 57 | } 58 | 59 | pub fn next_bounds(&mut self, f: u64, t: u64) -> u64 { 60 | f + self.next(t - f + 1) 61 | } 62 | } 63 | 64 | static mut RAND: Option = None; 65 | 66 | pub fn random() -> &'static mut Random { 67 | unsafe { 68 | if RAND.is_none() { 69 | RAND = Some(Random::new( 70 | (SystemTime::UNIX_EPOCH.elapsed().unwrap().as_nanos() & 0xFFFFFFFFFFFFFFFF) as u64, 71 | )); 72 | } 73 | RAND.as_mut().unwrap() 74 | } 75 | } 76 | 77 | pub trait Shuffle { 78 | fn shuffle(&mut self); 79 | } 80 | 81 | impl Shuffle for [T] { 82 | fn shuffle(&mut self) { 83 | for i in self.indices() { 84 | let at = (random().gen() % ((i + 1) as u64)) as usize; 85 | self.swap(i, at); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /c++/string/aho_corasick.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * build complete DFA and output link for pattern matching. 3 | * Usage: 4 | * add(id, begin, end, translation function): add word. 5 | * build(): build DFA from added words. 6 | * countMatch(...): example of pattern matching procedure. 7 | * 8 | * Example: 9 | * string P[] = { "abcabc", "bc", "c" }; 10 | * string match = "abcabc"; 11 | * AhoCorasick ac(26); 12 | * for (int i = 0; i < 3; i++) ac.add(i, P[i].begin(), P[i].end(), func); 13 | * ac.build(); 14 | * auto freq = ac.countMatch(match.begin(), match.end(), func); 15 | */ 16 | int func(char x) { 17 | return x - 'a'; 18 | } 19 | struct ahocorasick { 20 | const int alphabet; 21 | struct node { 22 | node() {} 23 | explicit node(int alphabet) : next(alphabet) {} 24 | vector next, report; 25 | int back = 0, output_link = 0; 26 | }; 27 | int maxid = 0; 28 | vector dfa; 29 | explicit ahocorasick(int alphabet) : alphabet(alphabet), dfa(1, node(alphabet)) { } 30 | template void add(int id, InIt first, InIt last, Fn func) { 31 | int cur = 0; 32 | for ( ; first != last; ++first) { 33 | auto s = func(*first); 34 | if (auto next = dfa[cur].next[s]) cur = next; 35 | else { 36 | cur = dfa[cur].next[s] = (int)dfa.size(); 37 | dfa.emplace_back(alphabet); 38 | } 39 | } 40 | dfa[cur].report.push_back(id); 41 | maxid = max(maxid, id); 42 | } 43 | void build() { 44 | queue q; 45 | vector visit(dfa.size()); 46 | visit[0] = 1; 47 | q.push(0); 48 | while(!q.empty()) { 49 | auto cur = q.front(); q.pop(); 50 | dfa[cur].output_link = dfa[cur].back; 51 | if (dfa[dfa[cur].back].report.empty()) 52 | dfa[cur].output_link = dfa[dfa[cur].back].output_link; 53 | for (int s = 0; s < alphabet; s++) { 54 | auto &next = dfa[cur].next[s]; 55 | if (next == 0) next = dfa[dfa[cur].back].next[s]; 56 | if (visit[next]) continue; 57 | if (cur) dfa[next].back = dfa[dfa[cur].back].next[s]; 58 | visit[next] = 1; 59 | q.push(next); 60 | } 61 | } 62 | } 63 | template vector countMatch(InIt first, InIt last, Fn func) { 64 | int cur = 0; 65 | vector ret(maxid+1); 66 | for (; first != last; ++first) { 67 | cur = dfa[cur].next[func(*first)]; 68 | for (int p = cur; p; p = dfa[p].output_link) 69 | for (auto id : dfa[p].report) ret[id]++; 70 | } 71 | return ret; 72 | } 73 | }; 74 | -------------------------------------------------------------------------------- /rust/graph/strongly_connected_components.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::bit_set::BitSet; 2 | use crate::graph::edges::edge::Edge; 3 | use crate::graph::edges::edge_trait::EdgeTrait; 4 | use crate::graph::graph::Graph; 5 | use crate::misc::recursive_function::{Callable, RecursiveFunction}; 6 | 7 | pub trait StronglyConnectedComponents { 8 | fn strongly_connected_components(&self) -> (Vec, Graph); 9 | } 10 | 11 | impl StronglyConnectedComponents for Graph { 12 | fn strongly_connected_components(&self) -> (Vec, Graph) { 13 | assert!(!E::REVERSABLE); 14 | let n = self.vertex_count(); 15 | let mut order = Vec::with_capacity(n); 16 | let mut color = vec![0; n]; 17 | let mut visited = BitSet::new(n); 18 | for i in 0..n { 19 | if !visited[i] { 20 | let mut first_dfs = RecursiveFunction::new(|f, vert| { 21 | if visited[vert] { 22 | return; 23 | } 24 | visited.set(vert); 25 | for e in self[vert].iter() { 26 | f.call(e.to()); 27 | } 28 | order.push(vert); 29 | }); 30 | first_dfs.call(i); 31 | } 32 | } 33 | visited.fill(false); 34 | let mut res = Graph::new(0); 35 | let mut index = 0usize; 36 | let mut next = vec![n; n]; 37 | let mut queue = Vec::with_capacity(n); 38 | let mut gt = Graph::new(n); 39 | for i in 0..n { 40 | for e in self[i].iter() { 41 | gt.add_edge(e.to(), Edge::new(i)); 42 | } 43 | } 44 | for i in (0..n).rev() { 45 | if !visited[order[i]] { 46 | let key = i; 47 | let mut second_dfs = RecursiveFunction::new(|f, vert| { 48 | if visited[vert] { 49 | if color[vert] != index && next[color[vert]] != key { 50 | next[color[vert]] = key; 51 | queue.push(color[vert]); 52 | } 53 | return; 54 | } 55 | color[vert] = index; 56 | visited.set(vert); 57 | for e in gt[vert].iter() { 58 | f.call(e.to()); 59 | } 60 | }); 61 | second_dfs.call(order[i]); 62 | res.add_vertices(1); 63 | for j in queue.drain(..) { 64 | res.add_edge(j, Edge::new(index)); 65 | } 66 | index += 1; 67 | } 68 | } 69 | (color, res) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /rust/numbers/num_traits/bit_ops.rs: -------------------------------------------------------------------------------- 1 | use crate::numbers::num_traits::zero_one::ZeroOne; 2 | use std::ops::{ 3 | BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, RangeInclusive, Shl, 4 | }; 5 | use std::ops::{ShlAssign, Shr, ShrAssign}; 6 | 7 | pub trait BitOps: 8 | Copy 9 | + BitAnd 10 | + BitAndAssign 11 | + BitOr 12 | + BitOrAssign 13 | + BitXor 14 | + BitXorAssign 15 | + Not 16 | + Shl 17 | + ShlAssign 18 | + Shr 19 | + ShrAssign 20 | + ZeroOne 21 | + PartialEq 22 | { 23 | fn bit(at: usize) -> Self { 24 | Self::one() << at 25 | } 26 | 27 | fn is_set(&self, at: usize) -> bool { 28 | (*self >> at & Self::one()) == Self::one() 29 | } 30 | 31 | fn set_bit(&mut self, at: usize) { 32 | *self |= Self::bit(at) 33 | } 34 | 35 | fn unset_bit(&mut self, at: usize) { 36 | *self &= !Self::bit(at) 37 | } 38 | 39 | #[must_use] 40 | fn with_bit(mut self, at: usize) -> Self { 41 | self.set_bit(at); 42 | self 43 | } 44 | 45 | #[must_use] 46 | fn without_bit(mut self, at: usize) -> Self { 47 | self.unset_bit(at); 48 | self 49 | } 50 | 51 | fn flip_bit(&mut self, at: usize) { 52 | *self ^= Self::bit(at) 53 | } 54 | 55 | fn all_bits(n: usize) -> Self { 56 | let mut res = Self::zero(); 57 | for i in 0..n { 58 | res.set_bit(i); 59 | } 60 | res 61 | } 62 | 63 | fn iter_all(n: usize) -> RangeInclusive { 64 | Self::zero()..=Self::all_bits(n) 65 | } 66 | } 67 | 68 | impl< 69 | T: Copy 70 | + BitAnd 71 | + BitAndAssign 72 | + BitOr 73 | + BitOrAssign 74 | + BitXor 75 | + BitXorAssign 76 | + Not 77 | + Shl 78 | + ShlAssign 79 | + Shr 80 | + ShrAssign 81 | + ZeroOne 82 | + PartialEq, 83 | > BitOps for T 84 | { 85 | } 86 | 87 | pub trait Bits: BitOps { 88 | fn bits() -> u32; 89 | } 90 | 91 | macro_rules! bits_integer_impl { 92 | ($($t: ident $bits: expr),+) => {$( 93 | impl Bits for $t { 94 | fn bits() -> u32 { 95 | $bits 96 | } 97 | } 98 | )+}; 99 | } 100 | 101 | 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); 102 | -------------------------------------------------------------------------------- /rust/misc/dirs.rs: -------------------------------------------------------------------------------- 1 | use crate::const_value_ref; 2 | use crate::misc::value_ref::ConstValueRef; 3 | use std::marker::PhantomData; 4 | 5 | pub struct Directions> { 6 | phantom: PhantomData, 7 | } 8 | 9 | impl> Directions { 10 | pub fn iter( 11 | row: usize, 12 | col: usize, 13 | n: usize, 14 | m: usize, 15 | ) -> impl Iterator { 16 | DirectionsIter:: { 17 | row, 18 | col, 19 | n, 20 | m, 21 | at: 0, 22 | phantom: Default::default(), 23 | } 24 | } 25 | 26 | pub fn go(row: usize, col: usize, dir: usize, n: usize, m: usize) -> (usize, usize) { 27 | let (dr, dc) = V::val()[dir]; 28 | let mut row = row as isize + dr; 29 | let mut col = col as isize + dc; 30 | if row < 0 { 31 | row = 0; 32 | } 33 | if row >= n as isize { 34 | row = n as isize - 1; 35 | } 36 | if col < 0 { 37 | col = 0; 38 | } 39 | if col >= m as isize { 40 | col = m as isize - 1; 41 | } 42 | (row as usize, col as usize) 43 | } 44 | } 45 | 46 | struct DirectionsIter> { 47 | row: usize, 48 | col: usize, 49 | n: usize, 50 | m: usize, 51 | at: usize, 52 | phantom: PhantomData, 53 | } 54 | 55 | impl> Iterator for DirectionsIter { 56 | type Item = (usize, usize); 57 | 58 | fn next(&mut self) -> Option { 59 | while self.at < V::val().len() { 60 | let n_row = (self.row as isize) + V::val()[self.at].0; 61 | let n_col = (self.col as isize) + V::val()[self.at].1; 62 | self.at += 1; 63 | if n_row >= 0 && (n_row as usize) < self.n && n_col >= 0 && (n_col as usize) < self.m { 64 | return Some((n_row as usize, n_col as usize)); 65 | } 66 | } 67 | None 68 | } 69 | } 70 | 71 | const_value_ref!( 72 | D4Dirs D4_DIRS_INNER: [(isize, isize); 4] as [(isize, isize)] = [ 73 | (0isize, 1isize), 74 | (1isize, 0isize), 75 | (0isize, -1isize), 76 | (-1isize, 0isize), 77 | ] 78 | ); 79 | 80 | pub type D4 = Directions; 81 | 82 | const_value_ref!( 83 | D8Dirs D8_DIRS_INNER: [(isize, isize); 8] as [(isize, isize)] = [ 84 | (0isize, 1isize), 85 | (1isize, 1isize), 86 | (1isize, 0isize), 87 | (1isize, -1isize), 88 | (0isize, -1isize), 89 | (-1isize, -1isize), 90 | (-1isize, 0isize), 91 | (-1isize, 1isize), 92 | ] 93 | ); 94 | 95 | pub type D8 = Directions; 96 | -------------------------------------------------------------------------------- /c++/math/fft_long.cpp: -------------------------------------------------------------------------------- 1 | typedef long long ll; 2 | const double PI = 3.1415926535897932384626433832795; 3 | 4 | namespace FFT { 5 | typedef complex base; 6 | void FFT(vector &v, bool inv) { 7 | vector w(v.size()); 8 | for (int i = 0; i < v.size(); i++) { 9 | int k = i&-i; 10 | if (i == k) { 11 | double ang = 2 * PI * i / v.size(); 12 | if (inv) ang *= -1; 13 | w[i] = base(cos(ang), sin(ang)); 14 | } 15 | else w[i] = w[i - k] * w[k]; 16 | } 17 | for (int i = 1, j = 0; i < v.size(); i++) { 18 | int bit = v.size() >> 1; 19 | for (; j >= bit; bit >>= 1) j -= bit; 20 | j += bit; 21 | if (i < j) swap(v[i], v[j]); 22 | } 23 | for (int i = 2; i <= v.size(); i <<= 1) { 24 | for (int j = 0; j < v.size(); j += i) { 25 | for (int k = 0; k < i / 2; k++) { 26 | base a = v[j + k], b = v[j + k + i / 2] * w[k * (v.size() / i)]; 27 | v[j + k] = a + b; 28 | v[j + k + i / 2] = a - b; 29 | } 30 | } 31 | } 32 | if (inv) { 33 | for (int i = 0; i < v.size(); i++) { 34 | v[i] /= v.size(); 35 | } 36 | } 37 | } 38 | vector mul(vector &v, vector &w) { 39 | vector fv(v.begin(), v.end()), fw(w.begin(), w.end()); 40 | int n = 1; 41 | while (n < max(v.size(), w.size())) n <<= 1; 42 | n <<= 1; 43 | fv.resize(n); 44 | fw.resize(n); 45 | FFT(fv, 0); 46 | FFT(fw, 0); 47 | for (int i = 0; i < n; i++) fv[i] *= fw[i]; 48 | FFT(fv, 1); 49 | vector ret(n); 50 | for (int i = 0; i < n; i++) ret[i] = round(fv[i].real()); 51 | return ret; 52 | } 53 | vector pw(vector &v) { 54 | vector fv(v.begin(), v.end()); 55 | int n = 1; 56 | while (n < v.size()) n <<= 1; 57 | n <<= 1; 58 | fv.resize(n); 59 | FFT(fv, 0); 60 | for (int i = 0; i < n; i++) fv[i] *= fv[i]; 61 | FFT(fv, 1); 62 | vector ret(n); 63 | for (int i = 0; i < n; i++) ret[i] = round(fv[i].real()); 64 | return ret; 65 | } 66 | vector solve(vector &v, vector &w, int b) { 67 | int n = 1; 68 | while (n < v.size() || n < w.size()) n <<= 1; 69 | n <<= 1; 70 | vector v1(n), v2(n), v3(n), v4(n), r1(n), r2(n), r3(n); 71 | for (int i = 0; i < v.size(); i++) { 72 | v1[i] = base(v[i] / b, 0); 73 | v2[i] = base(v[i] % b, 0); 74 | } 75 | for (int i = 0; i < w.size(); i++) { 76 | v3[i] = base(w[i] / b, 0); 77 | v4[i] = base(w[i] % b, 0); 78 | } 79 | FFT(v1, 0); FFT(v2, 0); FFT(v3, 0); FFT(v4, 0); 80 | for (int i = 0; i < n; i++) { 81 | r1[i] = v1[i] * v3[i]; 82 | r2[i] = v1[i] * v4[i] + v2[i] * v3[i]; 83 | r3[i] = v2[i] * v4[i]; 84 | } 85 | FFT(r1, 1); FFT(r2, 1); FFT(r3, 1); 86 | vector ret(n); 87 | for (int i = 0; i < n; i++) { 88 | ret[i] = (ll)round(r1[i].real()) * b * b + (ll)round(r2[i].real()) * b + (ll)round(r3[i].real()); 89 | } 90 | return ret; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /c++/graph/kcm_mcmf.cpp: -------------------------------------------------------------------------------- 1 | // precondition: there is no negative cycle. 2 | // usage: 3 | // MinCostFlow mcf(n); 4 | // for(each edges) mcf.addEdge(from, to, cost, capacity); 5 | // mcf.solve(source, sink); // min cost max flow 6 | // mcf.solve(source, sink, 0); // min cost flow 7 | // mcf.solve(source, sink, goal_flow); // min cost flow with total_flow >= goal_flow if possible 8 | struct MinCostFlow { 9 | typedef int cap_t; 10 | typedef int cost_t; 11 | 12 | bool iszerocap(cap_t cap) { return cap == 0; } 13 | 14 | struct edge { 15 | int target; 16 | cost_t cost; 17 | cap_t residual; 18 | cap_t cap; 19 | size_t revid; 20 | }; 21 | 22 | int n; 23 | vector> G; 24 | 25 | MinCostFlow(int n) : G(n), n(n) {} 26 | 27 | void addEdge(int s, int e, cost_t cost, cap_t cap) { 28 | if (s == e) return; 29 | edge forward{ e, cost, cap, cap, G[e].size() }; 30 | edge backward{ s, -cost, 0, 0, G[s].size() }; 31 | G[s].emplace_back(forward); 32 | G[e].emplace_back(backward); 33 | } 34 | 35 | pair augmentShortest(int s, int e, cap_t flow_limit) { 36 | auto infinite_cost = numeric_limits::max(); 37 | auto infinite_flow = numeric_limits::max(); 38 | vector> dist(n, make_pair(infinite_cost, 0)); 39 | vector from(n, -1), v(n); 40 | 41 | dist[s] = pair(0, infinite_flow); 42 | queue q; 43 | v[s] = 1; q.push(s); 44 | while (!q.empty()) { 45 | int cur = q.front(); 46 | v[cur] = 0; q.pop(); 47 | for (const auto& e : G[cur]) { 48 | if (iszerocap(e.residual)) continue; 49 | auto next = e.target; 50 | auto ncost = dist[cur].first + e.cost; 51 | auto nflow = min(dist[cur].second, e.residual); 52 | if (dist[next].first > ncost) { 53 | dist[next] = make_pair(ncost, nflow); 54 | from[next] = e.revid; 55 | if (v[next]) continue; 56 | v[next] = 1; q.push(next); 57 | } 58 | } 59 | } 60 | 61 | auto p = e; 62 | auto pathcost = dist[p].first; 63 | auto flow = dist[p].second; 64 | if (iszerocap(flow) || (flow_limit <= 0 && pathcost >= 0)) return pair(0, 0); 65 | if (flow_limit > 0) flow = min(flow, flow_limit); 66 | 67 | while (from[p] != -1) { 68 | auto nedge = from[p]; 69 | auto np = G[p][nedge].target; 70 | auto fedge = G[p][nedge].revid; 71 | G[p][nedge].residual += flow; 72 | G[np][fedge].residual -= flow; 73 | p = np; 74 | } 75 | return make_pair(pathcost * flow, flow); 76 | } 77 | 78 | pair solve(int s, int e, cap_t flow_minimum = numeric_limits::max()) { 79 | cost_t total_cost = 0; 80 | cap_t total_flow = 0; 81 | for (;;) { 82 | auto res = augmentShortest(s, e, flow_minimum - total_flow); 83 | if (res.second <= 0) break; 84 | total_cost += res.first; 85 | total_flow += res.second; 86 | } 87 | return make_pair(total_cost, total_flow); 88 | } 89 | }; 90 | -------------------------------------------------------------------------------- /c++/graph/FAST Mincost Flow.cpp: -------------------------------------------------------------------------------- 1 | const int inf = 0x3f3f3f3f; 2 | const int MAXN = 2505; 3 | const int MAXM = 100005; 4 | //variable 'ending' determines maxflow or not. 5 | struct MinCostFlow { 6 | int sz, n, ending; 7 | int st, en, maxflow, mincost; 8 | bool vis[MAXN]; 9 | int net[MAXN], pre[MAXN], cur[MAXN], dis[MAXN], Q[100 * MAXN], fr, re; 10 | struct EDGE { 11 | int v, cap, cost, next; 12 | EDGE() {} 13 | EDGE(int a, int b, int c, int d) { 14 | v = a, cap = b, cost = c, next = d; 15 | } 16 | } E[MAXM]; 17 | void init(int _n) { 18 | ending = 0; 19 | n = _n, sz = 0; 20 | memset(net, -1, sizeof(net)); 21 | } 22 | void addEdge(int u, int v, int cost, int cap) { 23 | E[sz] = EDGE(v, cap, cost, net[u]); 24 | net[u] = sz++; 25 | E[sz] = EDGE(u, 0, -cost, net[v]); 26 | net[v] = sz++; 27 | } 28 | bool adjust() { 29 | int v, min = inf; 30 | for (int i = 0; i <= n; i++) { 31 | if (!vis[i]) continue; 32 | for (int j = net[i]; v = E[j].v, j != -1; j = E[j].next) 33 | if (E[j].cap && !vis[v] && dis[v] - dis[i] + E[j].cost < min) 34 | min = dis[v] - dis[i] + E[j].cost; 35 | } 36 | if (min == inf) return false; 37 | for (int i = 0; i <= n; i++) if (vis[i]) cur[i] = net[i], vis[i] = false, dis[i] += min; 38 | return true; 39 | } 40 | int augment(int i, int flow) { 41 | if (i == en) { 42 | if (dis[st] < 0) mincost += dis[st] * flow; 43 | else ending = 1; //mcf, not mcmf 44 | maxflow += flow; 45 | return flow; 46 | } 47 | vis[i] = true; 48 | for (int j = cur[i], v; v = E[j].v, j != -1; j = E[j].next) { 49 | if (!E[j].cap) continue; 50 | if (vis[v] || dis[v] + E[j].cost != dis[i]) continue; 51 | int delta = augment(v, std::min(flow, E[j].cap)); 52 | if (delta) { 53 | E[j].cap -= delta; 54 | E[j ^ 1].cap += delta; 55 | cur[i] = j; 56 | return delta; 57 | } 58 | } 59 | return 0; 60 | } 61 | void spfa() { 62 | int u, v; 63 | for (int i = 0; i <= n; i++) vis[i] = false, dis[i] = inf; 64 | dis[st] = 0; 65 | Q[fr = re = 0] = st; 66 | vis[st] = true; 67 | while (fr <= re) { 68 | u = Q[fr++]; 69 | vis[u] = false; 70 | for (int i = net[u]; v = E[i].v, i != -1; i = E[i].next) { 71 | if (!E[i].cap || dis[v] <= dis[u] + E[i].cost) continue; 72 | dis[v] = dis[u] + E[i].cost; 73 | if (!vis[v]) { 74 | vis[v] = true; 75 | Q[++re] = v; 76 | if (dis[Q[fr]] > dis[Q[re]]) swap(Q[fr], Q[re]); 77 | } 78 | } 79 | } 80 | for (int i = 0; i <= n; i++) dis[i] = dis[en] - dis[i]; 81 | } 82 | int solve(int s, int t, int need) { 83 | st = s, en = t; 84 | spfa(); 85 | mincost = maxflow = 0; 86 | for (int i = 0; i <= n; i++) vis[i] = false, cur[i] = net[i]; 87 | do { 88 | while (augment(st, inf)) { 89 | if (ending) return mincost; //mcf, not mcmf 90 | memset(vis, false, sizeof(vis)); 91 | } 92 | } while (adjust()); 93 | return mincost; 94 | } 95 | }; 96 | -------------------------------------------------------------------------------- /c++/data_stucture/Splay.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef long long ll; 4 | struct NODE { 5 | NODE *l, *r, *p; 6 | ll cnt, value, sum, lazy; 7 | NODE(NODE *l, NODE *r, NODE *p, ll cnt, ll value, ll sum, ll lazy) : 8 | l(l), r(r), p(p), cnt(cnt), value(value), sum(sum), lazy(lazy) {} 9 | } *root; 10 | void Update(NODE *x){ 11 | x->cnt = 1; 12 | x->sum = x->value; 13 | if (x->l){ 14 | x->cnt += x->l->cnt; 15 | x->sum += x->l->sum; 16 | } 17 | if (x->r){ 18 | x->cnt += x->r->cnt; 19 | x->sum += x->r->sum; 20 | } 21 | } 22 | void Lazy(NODE *x){ 23 | x->value += x->lazy; 24 | if (x->l){ 25 | x->l->lazy += x->lazy; 26 | x->l->sum += x->l->cnt*x->lazy; 27 | } 28 | if (x->r){ 29 | x->r->lazy += x->lazy; 30 | x->r->sum += x->r->cnt*x->lazy; 31 | } 32 | x->lazy = 0; 33 | } 34 | void Rotate(NODE *x){ 35 | NODE *p=x->p, *b; 36 | if (p->l == x){ 37 | p->l = b = x->r; 38 | x->r = p; 39 | } 40 | else{ 41 | p->r = b = x->l; 42 | x->l = p; 43 | } 44 | if (b)b->p = p; 45 | x->p = p->p; 46 | p->p = x; 47 | (x->p ? ((x->p->l == p) ? x->p->l : x->p->r) : root) = x; 48 | Update(p); 49 | Update(x); 50 | } 51 | void Splay(NODE *x){ 52 | NODE *p, *g; 53 | while (x->p){ 54 | p = x->p; 55 | g = p->p; 56 | if (g)Rotate(((p->l == x) == (g->l == p)) ? p : x); 57 | Rotate(x); 58 | } 59 | } 60 | void find_kth(int k){ 61 | NODE *now = root; 62 | Lazy(now); 63 | while (1) { 64 | while (now->l&&now->l->cnt > k){ 65 | now = now->l; 66 | Lazy(now); 67 | } 68 | if (now->l)k -= now->l->cnt; 69 | if (k == 0) break; 70 | k--; 71 | now = now->r; 72 | Lazy(now); 73 | } 74 | Splay(now); 75 | } 76 | void init(int n){ 77 | NODE *x; 78 | x = root = new NODE(NULL, NULL, NULL, n + 2, 0, 0, 0); 79 | for (int i = 0; i < n + 1; i++){ 80 | x->r = new NODE(NULL, NULL, x, n + 1 - i, 0, 0, 0); 81 | x = x->r; 82 | } 83 | } 84 | void Interval(int l, int r){ 85 | NODE *x; 86 | find_kth(l - 1); 87 | x = root; 88 | root = root->r; 89 | root->p = NULL; 90 | find_kth(r - l + 1); 91 | root->p = x; 92 | x->r = root; 93 | root = x; 94 | } 95 | void insert_g(int l, int r, ll g){ 96 | Interval(l, r); 97 | NODE *x = root->r->l; 98 | x->lazy += g; 99 | x->sum += x->cnt*g; 100 | } 101 | ll get_sum(ll l, ll r){ 102 | Interval(l, r); 103 | return root->r->l->sum; 104 | } 105 | ll S[1000005]; 106 | int main(){ 107 | int n, m, k; 108 | scanf("%d%d%d", &n, &m, &k); 109 | for (int i = 1; i <= n; i++){ 110 | int x; scanf("%d", &x); 111 | S[i] = S[i - 1] + x; 112 | } 113 | init(n); 114 | for (int i = 0; i < m + k; i++){ 115 | int type, s, e; ll g; 116 | scanf("%d%d%d", &type, &s, &e); 117 | if (type == 1) { 118 | scanf("%lld", &g); 119 | insert_g(s, e, g); 120 | } 121 | else printf("%lld\n", S[e]-S[s-1] + get_sum(s, e)); 122 | } 123 | } -------------------------------------------------------------------------------- /rust/collections/persistent_fenwick.rs: -------------------------------------------------------------------------------- 1 | use crate::collections::min_max::MinimMaxim; 2 | use crate::collections::slice_ext::bounds::Bounds; 3 | use crate::numbers::num_traits::add_sub::AddSub; 4 | use crate::numbers::num_traits::zero_one::ZeroOne; 5 | use std::cmp::Ordering; 6 | 7 | #[derive(Clone)] 8 | pub struct PersistentFenwickTree { 9 | base: E, 10 | value: Vec>>, 11 | } 12 | 13 | #[derive(Clone)] 14 | struct Value { 15 | epoch: E, 16 | value: T, 17 | } 18 | 19 | impl PartialEq for Value { 20 | fn eq(&self, other: &Self) -> bool { 21 | self.epoch.eq(&other.epoch) 22 | } 23 | } 24 | 25 | impl PartialOrd for Value { 26 | fn partial_cmp(&self, other: &Self) -> Option { 27 | self.epoch.partial_cmp(&other.epoch) 28 | } 29 | } 30 | 31 | impl PersistentFenwickTree { 32 | pub fn new(size: usize, base: E) -> Self { 33 | Self { 34 | base, 35 | value: vec![ 36 | vec![Value { 37 | value: T::zero(), 38 | epoch: base 39 | }]; 40 | size 41 | ], 42 | } 43 | } 44 | 45 | pub fn get_to(&self, mut to: usize, epoch: E) -> T { 46 | if epoch < self.base { 47 | panic!("Queried epoch before base"); 48 | } 49 | to.minim(self.value.len()); 50 | let mut result = T::zero(); 51 | while to > 0 { 52 | to -= 1; 53 | let mut pos = self.value[to].as_slice().lower_bound(&Value { 54 | epoch, 55 | value: T::zero(), 56 | }); 57 | if pos == self.value[to].len() || self.value[to][pos].epoch != epoch { 58 | pos -= 1; 59 | } 60 | result += self.value[to][pos].value; 61 | to &= to + 1; 62 | } 63 | result 64 | } 65 | 66 | pub fn get(&self, from: usize, to: usize, epoch: E) -> T { 67 | if from >= to { 68 | T::zero() 69 | } else { 70 | self.get_to(to, epoch) - self.get_to(from, epoch) 71 | } 72 | } 73 | 74 | pub fn add(&mut self, mut at: usize, v: T, epoch: E) { 75 | while at < self.value.len() { 76 | if self.value[at].last().unwrap().epoch == epoch { 77 | self.value[at].last_mut().unwrap().value += v; 78 | } else { 79 | let vat = self.value[at].last().unwrap().value + v; 80 | self.value[at].push(Value { value: vat, epoch }); 81 | } 82 | at |= at + 1; 83 | } 84 | } 85 | 86 | pub fn iter(&self, epoch: E) -> impl Iterator + '_ { 87 | (0..self.value.len()) 88 | // edition 2021 89 | .map(move |i| self.get(i, i + 1, epoch)) 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /c++/graph/hungarian.cpp: -------------------------------------------------------------------------------- 1 | // Kuhn munkres algorithm by MolaMola(cki86201, dotorya, zigui) 2 | // Computes a maximum weight matching in a bipartite graph 3 | // Time Complexity : O(N^3) 4 | // test : https://hochiminh17.kattis.com/problems/engaging 5 | 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | const int INF = 1e9; 12 | 13 | int in[1005][1005]; 14 | int mats[1005], matt[1005]; 15 | int Ls[1005], Lt[1005]; 16 | int revs[1005], revt[1005]; 17 | int valt[1005]; 18 | bool chks[1005], chkt[1005]; 19 | 20 | vector Vu; 21 | void vpush(int p, int N) { 22 | chks[p] = 1; 23 | for (int i = 1; i <= N; i++) { 24 | if (!valt[i]) continue; 25 | if (valt[i] > Ls[p] + Lt[i] - in[p][i]) { 26 | valt[i] = Ls[p] + Lt[i] - in[p][i]; 27 | revt[i] = p; 28 | if (!valt[i]) Vu.push_back(i); 29 | } 30 | } 31 | } 32 | 33 | int main() { 34 | int N, M, K, i, j, k; 35 | scanf("%d%d%d", &M, &N, &K); 36 | N = max(N, M); 37 | for (int i = 1; i <= K; i++) { 38 | int x, y, w; scanf("%d%d%d", &x, &y, &w); 39 | in[x][y] = max(in[x][y], w); 40 | } 41 | for (i = 1; i <= N; i++) Lt[i] = -INF; 42 | for (i = 1; i <= N; i++) for (j = 1; j <= N; j++) Lt[j] = max(Lt[j], in[i][j]); 43 | for (i = 1; i <= N; i++) { 44 | for (j = 1; j <= N; j++) chks[j] = chkt[j] = 0; 45 | for (j = 1; j <= N; j++) valt[j] = INF; 46 | for (j = 1; j <= N; j++) revs[j] = revt[j] = 0; 47 | int p = 0; 48 | for (j = 1; j <= N; j++) 49 | if (!mats[j]) 50 | break; 51 | p = j; 52 | vpush(p, N); 53 | while (1) { 54 | if (!Vu.empty()) { 55 | int t = Vu.back(); 56 | Vu.pop_back(); 57 | chkt[t] = 1; 58 | if (!matt[t]) { 59 | vector Vu2; 60 | Vu2.push_back(t); 61 | while (1) { 62 | Vu2.push_back(revt[Vu2.back()]); 63 | if (Vu2.back() == p) break; 64 | Vu2.push_back(revs[Vu2.back()]); 65 | } 66 | reverse(Vu2.begin(), Vu2.end()); 67 | for (j = 0; j < Vu2.size(); j += 2) { 68 | int s = Vu2[j], t = Vu2[j + 1]; 69 | mats[s] = t; 70 | matt[t] = s; 71 | } 72 | break; 73 | } 74 | else { 75 | int s = matt[t]; 76 | revs[s] = t; 77 | vpush(s, N); 78 | } 79 | } 80 | else { 81 | int mn = INF; 82 | for (j = 1; j <= N; j++) if (!chkt[j]) mn = min(mn, valt[j]); 83 | for (j = 1; j <= N; j++) { 84 | if (chks[j]) Ls[j] -= mn; 85 | if (chkt[j]) Lt[j] += mn; 86 | else { valt[j] -= mn; if (valt[j] == 0) Vu.push_back(j); } 87 | } 88 | } 89 | } 90 | Vu.clear(); 91 | } 92 | int ans = 0; 93 | vector > res; 94 | for (i = 1; i <= N; i++) { 95 | ans += Ls[i] + Lt[i]; 96 | if (in[i][mats[i]]) res.push_back({ i, mats[i] }); 97 | } 98 | printf("%d\n", ans); 99 | printf("%d\n", res.size()); 100 | for (auto &t : res) printf("%d %d\n", t.first, t.second); 101 | } -------------------------------------------------------------------------------- /rust/misc/memo/memoization.rs: -------------------------------------------------------------------------------- 1 | use crate::misc::recursive_function::Callable; 2 | use crate::misc::recursive_function::Callable2; 3 | use crate::misc::recursive_function::Callable3; 4 | use crate::misc::recursive_function::Callable4; 5 | use crate::misc::recursive_function::Callable5; 6 | use crate::misc::recursive_function::Callable6; 7 | use crate::misc::recursive_function::Callable7; 8 | use crate::misc::recursive_function::Callable8; 9 | use crate::misc::recursive_function::Callable9; 10 | use std::collections::HashMap; 11 | use std::hash::Hash; 12 | 13 | macro_rules! memoization { 14 | ($name: ident, $trait: ident, ($($type: ident $arg: ident,)*)) => { 15 | pub struct $name 16 | where 17 | F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output, 18 | { 19 | f: std::cell::UnsafeCell, 20 | res: HashMap<($($type, )*), Output>, 21 | } 22 | 23 | impl $name 24 | where 25 | F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output, 26 | { 27 | pub fn new(f: F) -> Self { 28 | Self { 29 | f: std::cell::UnsafeCell::new(f), 30 | res: HashMap::new(), 31 | } 32 | } 33 | } 34 | 35 | impl $trait<$($type, )*Output> for $name 36 | where 37 | F: FnMut(&mut dyn $trait<$($type, )*Output>, $($type, )*) -> Output, 38 | { 39 | fn call(&mut self, $($arg: $type, )*) -> Output { 40 | match self.res.get(&($($arg, )*)).cloned() { 41 | None => { 42 | let res = unsafe { (*self.f.get())(self, $($arg, )*) }; 43 | self.res.insert(($($arg, )*), res.clone()); 44 | res 45 | } 46 | Some(res) => res, 47 | } 48 | } 49 | } 50 | } 51 | } 52 | 53 | memoization!(Memoization, Callable, (Arg arg,)); 54 | memoization!(Memoization2, Callable2, (Arg1 arg1, Arg2 arg2,)); 55 | memoization!(Memoization3, Callable3, (Arg1 arg1, Arg2 arg2, Arg3 arg3,)); 56 | memoization!(Memoization4, Callable4, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4,)); 57 | memoization!(Memoization5, Callable5, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5,)); 58 | memoization!(Memoization6, Callable6, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6,)); 59 | memoization!(Memoization7, Callable7, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7,)); 60 | memoization!(Memoization8, Callable8, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8,)); 61 | memoization!(Memoization9, Callable9, (Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, Arg8 arg8, Arg9 arg9,)); 62 | -------------------------------------------------------------------------------- /rust/geometry/line.rs: -------------------------------------------------------------------------------- 1 | use crate::geometry::point::Point; 2 | use crate::numbers::num_traits::field::Field; 3 | use crate::numbers::num_traits::real::RealTrait; 4 | use crate::numbers::num_traits::ring::Ring; 5 | 6 | #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] 7 | pub struct Line { 8 | pub a: T, 9 | pub b: T, 10 | pub c: T, 11 | } 12 | 13 | impl Line { 14 | pub fn new(a: T, b: T, c: T) -> Self { 15 | Self { a, b, c } 16 | } 17 | } 18 | 19 | impl Line { 20 | pub fn value(&self, p: Point) -> T { 21 | self.a * p.x + self.b * p.y + self.c 22 | } 23 | 24 | pub fn parallel(&self, p: Point) -> Line { 25 | Line::new(self.a, self.b, T::zero() - self.a * p.x - self.b * p.y) 26 | } 27 | 28 | pub fn perpendicular(&self, p: Point) -> Line { 29 | Line::new( 30 | T::zero() - self.b, 31 | self.a, 32 | T::zero() + self.b * p.x - self.a * p.y, 33 | ) 34 | } 35 | } 36 | 37 | impl Line { 38 | pub fn is_parallel(&self, other: Line) -> bool { 39 | self.a * other.b == self.b * other.a 40 | } 41 | 42 | pub fn is_perpendicular(&self, other: Line) -> bool { 43 | self.a * other.a + self.b * other.b == T::zero() 44 | } 45 | } 46 | 47 | impl Line { 48 | pub fn intersect(&self, other: Line) -> Point { 49 | let det = self.a * other.b - other.a * self.b; 50 | let x = (self.b * other.c - other.b * self.c) / det; 51 | let y = (other.a * self.c - self.a * other.c) / det; 52 | Point::new(x, y) 53 | } 54 | 55 | pub fn square_dist_point(&self, p: Point) -> T { 56 | let val = self.value(p); 57 | val * val / (self.a * self.a + self.b * self.b) 58 | } 59 | } 60 | 61 | impl Line { 62 | pub fn contains(&self, p: Point) -> bool { 63 | self.value(p) == T::zero() 64 | } 65 | } 66 | 67 | impl Line { 68 | pub fn new_real(a: T, b: T, c: T) -> Self { 69 | let h = T::hypot(a, b); 70 | Self { 71 | a: a / h, 72 | b: b / h, 73 | c: c / h, 74 | } 75 | } 76 | 77 | pub fn dist_point(&self, p: Point) -> T { 78 | self.square_dist_point(p).sqrt() 79 | } 80 | 81 | pub fn contains_real(&self, p: Point) -> bool { 82 | self.dist_point(p) < T::epsilon() 83 | } 84 | 85 | pub fn is_parallel_real(&self, other: Line) -> bool { 86 | (self.a * other.b - self.b * other.a).abs() < T::epsilon() 87 | } 88 | 89 | pub fn is_perpendicular_real(&self, other: Line) -> bool { 90 | (self.a * other.a + self.b * other.b).abs() < T::epsilon() 91 | } 92 | 93 | pub fn canonize(&mut self) { 94 | let h = T::hypot(self.a, self.b); 95 | self.a /= h; 96 | self.b /= h; 97 | self.c /= h; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /rust/graph/edges/weighted_edge.rs: -------------------------------------------------------------------------------- 1 | use crate::graph::edges::edge_id::{EdgeId, NoId, WithId}; 2 | use crate::graph::edges::edge_trait::EdgeTrait; 3 | use crate::graph::edges::weighted_edge_trait::WeightedEdgeTrait; 4 | use crate::graph::graph::Graph; 5 | use crate::io::input::{Input, Readable}; 6 | use crate::numbers::num_traits::add_sub::Addable; 7 | use crate::numbers::num_traits::zero_one::ZeroOne; 8 | 9 | #[derive(Clone)] 10 | pub struct WeightedEdgeRaw { 11 | to: u32, 12 | weight: W, 13 | id: Id, 14 | } 15 | 16 | impl WeightedEdgeRaw { 17 | pub fn new(to: usize, w: W) -> Self { 18 | Self { 19 | to: to as u32, 20 | weight: w, 21 | id: Id::new(), 22 | } 23 | } 24 | } 25 | 26 | impl EdgeTrait for WeightedEdgeRaw { 27 | const REVERSABLE: bool = false; 28 | 29 | fn to(&self) -> usize { 30 | self.to as usize 31 | } 32 | 33 | fn id(&self) -> usize { 34 | self.id.id() 35 | } 36 | 37 | fn set_id(&mut self, id: usize) { 38 | self.id.set_id(id); 39 | } 40 | 41 | fn reverse_id(&self) -> usize { 42 | panic!("no reverse") 43 | } 44 | 45 | fn set_reverse_id(&mut self, _: usize) { 46 | panic!("no reverse") 47 | } 48 | 49 | fn reverse_edge(&self, _: usize) -> Self { 50 | panic!("no reverse") 51 | } 52 | } 53 | 54 | impl WeightedEdgeTrait 55 | for WeightedEdgeRaw 56 | { 57 | fn weight(&self) -> W { 58 | self.weight 59 | } 60 | 61 | fn weight_mut(&mut self) -> &mut W { 62 | &mut self.weight 63 | } 64 | } 65 | 66 | pub type WeightedEdge = WeightedEdgeRaw; 67 | pub type WeightedEdgeWithId = WeightedEdgeRaw; 68 | 69 | pub trait ReadWeightedEdgeGraph { 70 | fn read_graph( 71 | &mut self, 72 | n: usize, 73 | m: usize, 74 | ) -> Graph>; 75 | } 76 | 77 | impl ReadWeightedEdgeGraph for Input<'_> { 78 | fn read_graph( 79 | &mut self, 80 | n: usize, 81 | m: usize, 82 | ) -> Graph> { 83 | let mut graph = Graph::new(n); 84 | for _ in 0..m { 85 | graph.add_edge(self.read(), WeightedEdgeRaw::new(self.read(), self.read())); 86 | } 87 | graph 88 | } 89 | } 90 | 91 | impl Readable 92 | for Graph> 93 | { 94 | fn read(input: &mut Input) -> Self { 95 | let n = input.read(); 96 | let m = input.read(); 97 | ::read_graph(input, n, m) 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /rust/graph/edges/weighted_flow_edge.rs: -------------------------------------------------------------------------------- 1 | use crate::graph::edges::edge_id::{EdgeId, NoId, WithId}; 2 | use crate::graph::edges::edge_trait::EdgeTrait; 3 | use crate::graph::edges::flow_edge_trait::FlowEdgeTrait; 4 | use crate::graph::edges::weighted_edge_trait::WeightedEdgeTrait; 5 | use crate::graph::graph::Graph; 6 | use crate::numbers::num_traits::add_sub::{AddSub, Addable}; 7 | use crate::numbers::num_traits::zero_one::ZeroOne; 8 | use std::ops::Neg; 9 | 10 | #[derive(Clone)] 11 | pub struct WeightedFlowEdgeRaw< 12 | W: Addable + Neg + Copy + ZeroOne, 13 | C: AddSub + PartialOrd + Copy + ZeroOne, 14 | Id: EdgeId, 15 | > { 16 | to: u32, 17 | weight: W, 18 | capacity: C, 19 | reverse_id: u32, 20 | id: Id, 21 | } 22 | 23 | impl< 24 | W: Addable + Neg + Copy + ZeroOne, 25 | C: AddSub + PartialOrd + Copy + ZeroOne, 26 | Id: EdgeId, 27 | > WeightedFlowEdgeRaw 28 | { 29 | pub fn new(to: usize, w: W, c: C) -> Self { 30 | Self { 31 | to: to as u32, 32 | weight: w, 33 | capacity: c, 34 | reverse_id: 0, 35 | id: Id::new(), 36 | } 37 | } 38 | } 39 | 40 | impl< 41 | W: Addable + Neg + Copy + ZeroOne, 42 | C: AddSub + PartialOrd + Copy + ZeroOne, 43 | Id: EdgeId, 44 | > EdgeTrait for WeightedFlowEdgeRaw 45 | { 46 | const REVERSABLE: bool = true; 47 | 48 | fn to(&self) -> usize { 49 | self.to as usize 50 | } 51 | 52 | fn id(&self) -> usize { 53 | self.id.id() 54 | } 55 | 56 | fn set_id(&mut self, id: usize) { 57 | self.id.set_id(id); 58 | } 59 | 60 | fn reverse_id(&self) -> usize { 61 | self.reverse_id as usize 62 | } 63 | 64 | fn set_reverse_id(&mut self, reverse_id: usize) { 65 | self.reverse_id = reverse_id as u32; 66 | } 67 | 68 | fn reverse_edge(&self, from: usize) -> Self { 69 | Self::new(from, -self.weight, C::zero()) 70 | } 71 | } 72 | 73 | impl< 74 | W: Addable + Neg + Copy + ZeroOne, 75 | C: AddSub + PartialOrd + Copy + ZeroOne, 76 | Id: EdgeId, 77 | > WeightedEdgeTrait for WeightedFlowEdgeRaw 78 | { 79 | fn weight(&self) -> W { 80 | self.weight 81 | } 82 | 83 | fn weight_mut(&mut self) -> &mut W { 84 | &mut self.weight 85 | } 86 | } 87 | 88 | impl< 89 | W: Addable + Neg + Copy + ZeroOne, 90 | C: AddSub + PartialOrd + Copy + ZeroOne, 91 | Id: EdgeId, 92 | > FlowEdgeTrait for WeightedFlowEdgeRaw 93 | { 94 | fn capacity(&self) -> C { 95 | self.capacity 96 | } 97 | 98 | fn capacity_mut(&mut self) -> &mut C { 99 | &mut self.capacity 100 | } 101 | 102 | fn flow(&self, graph: &Graph) -> C { 103 | graph[self.to as usize][self.reverse_id as usize].capacity 104 | } 105 | } 106 | 107 | pub type WeightedFlowEdge = WeightedFlowEdgeRaw; 108 | pub type WeightedFlowEdgeWithId = WeightedFlowEdgeRaw; 109 | -------------------------------------------------------------------------------- /rust/graph/edges/flow_edge.rs: -------------------------------------------------------------------------------- 1 | use crate::graph::edges::edge_id::{EdgeId, NoId, WithId}; 2 | use crate::graph::edges::edge_trait::EdgeTrait; 3 | use crate::graph::edges::flow_edge_trait::FlowEdgeTrait; 4 | use crate::graph::graph::Graph; 5 | use crate::io::input::{Input, Readable}; 6 | use crate::numbers::num_traits::add_sub::AddSub; 7 | use crate::numbers::num_traits::zero_one::ZeroOne; 8 | 9 | #[derive(Clone)] 10 | pub struct FlowEdgeRaw { 11 | to: u32, 12 | capacity: C, 13 | reverse_id: u32, 14 | id: Id, 15 | } 16 | 17 | impl FlowEdgeRaw { 18 | pub fn new(to: usize, c: C) -> Self { 19 | Self { 20 | to: to as u32, 21 | capacity: c, 22 | reverse_id: 0, 23 | id: Id::new(), 24 | } 25 | } 26 | } 27 | 28 | impl EdgeTrait for FlowEdgeRaw { 29 | const REVERSABLE: bool = true; 30 | 31 | fn to(&self) -> usize { 32 | self.to as usize 33 | } 34 | 35 | fn id(&self) -> usize { 36 | self.id.id() 37 | } 38 | 39 | fn set_id(&mut self, id: usize) { 40 | self.id.set_id(id); 41 | } 42 | 43 | fn reverse_id(&self) -> usize { 44 | self.reverse_id as usize 45 | } 46 | 47 | fn set_reverse_id(&mut self, reverse_id: usize) { 48 | self.reverse_id = reverse_id as u32; 49 | } 50 | 51 | fn reverse_edge(&self, from: usize) -> Self { 52 | Self::new(from, C::zero()) 53 | } 54 | } 55 | 56 | impl FlowEdgeTrait for FlowEdgeRaw { 57 | fn capacity(&self) -> C { 58 | self.capacity 59 | } 60 | 61 | fn capacity_mut(&mut self) -> &mut C { 62 | &mut self.capacity 63 | } 64 | 65 | fn flow(&self, graph: &Graph) -> C { 66 | graph[self.to as usize][self.reverse_id as usize].capacity 67 | } 68 | } 69 | 70 | pub type FlowEdge = FlowEdgeRaw; 71 | pub type FlowEdgeWithId = FlowEdgeRaw; 72 | 73 | pub trait ReadFlowEdgeGraph { 74 | fn read_graph( 75 | &mut self, 76 | n: usize, 77 | m: usize, 78 | ) -> Graph>; 79 | } 80 | 81 | impl ReadFlowEdgeGraph for Input<'_> { 82 | fn read_graph( 83 | &mut self, 84 | n: usize, 85 | m: usize, 86 | ) -> Graph> { 87 | let mut graph = Graph::new(n); 88 | for _ in 0..m { 89 | graph.add_edge(self.read(), FlowEdgeRaw::new(self.read(), self.read())); 90 | } 91 | graph 92 | } 93 | } 94 | 95 | impl Readable 96 | for Graph> 97 | { 98 | fn read(input: &mut Input) -> Self { 99 | let n = input.read(); 100 | let m = input.read(); 101 | ::read_graph(input, n, m) 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /rust/numbers/primes/prime.rs: -------------------------------------------------------------------------------- 1 | use crate::misc::random::random; 2 | use crate::misc::value::DynamicValue; 3 | use crate::numbers::gcd::gcd; 4 | use crate::numbers::mod_int::ModInt; 5 | use crate::numbers::num_traits::primitive::Primitive; 6 | use crate::numbers::num_traits::zero_one::ZeroOne; 7 | use crate::numbers::number_ext::Power; 8 | use crate::{dynamic_value, when}; 9 | 10 | pub fn is_prime(n: impl Primitive) -> bool { 11 | let n = n.to(); 12 | if n <= 1 { 13 | return false; 14 | } 15 | let mut s = 0; 16 | let mut d = n - 1; 17 | while d % 2 == 0 { 18 | s += 1; 19 | d >>= 1; 20 | } 21 | if s == 0 { 22 | return n == 2; 23 | } 24 | dynamic_value!(IsPrimeModule: i64 = n); 25 | type Mod = ModInt; 26 | for _ in 0..20 { 27 | let a = Mod::new(random().next(n as u64) as i64); 28 | if a == Mod::zero() { 29 | continue; 30 | } 31 | if a.power(d) == Mod::one() { 32 | continue; 33 | } 34 | let mut dd = d; 35 | let mut good = true; 36 | for _ in 0..s { 37 | if a.power(dd) + Mod::one() == Mod::zero() { 38 | good = false; 39 | break; 40 | } 41 | dd *= 2; 42 | } 43 | if good { 44 | return false; 45 | } 46 | } 47 | true 48 | } 49 | 50 | pub fn next_prime(mut n: i64) -> i64 { 51 | if n <= 2 { 52 | return 2; 53 | } 54 | n += 1 - (n & 1); 55 | while !is_prime(n) { 56 | n += 2; 57 | } 58 | n 59 | } 60 | 61 | fn brent(n: i64, x0: i64, c: i64) -> i64 { 62 | dynamic_value!(ModVal: i64 = n); 63 | type Mod = ModInt; 64 | let mut x = Mod::new(x0); 65 | let c = Mod::new(c); 66 | let mut g = 1; 67 | let mut q = Mod::one(); 68 | let mut xs = Mod::zero(); 69 | let mut y = Mod::zero(); 70 | let m = 128i64; 71 | let mut l = 1; 72 | while g == 1 { 73 | y = x; 74 | for _ in 1..l { 75 | x = x * x + c; 76 | } 77 | let mut k = 0; 78 | while k < l && g == 1 { 79 | xs = x; 80 | for _ in 0..m.min(l - k) { 81 | x = x * x + c; 82 | q *= y - x; 83 | } 84 | g = gcd(q.val(), n); 85 | k += m; 86 | } 87 | l *= 2; 88 | } 89 | if g == n { 90 | loop { 91 | xs = xs * xs + c; 92 | g = gcd((xs - y).val(), n); 93 | if g != 1 { 94 | break; 95 | } 96 | } 97 | } 98 | g 99 | } 100 | 101 | pub fn find_divisor(n: i64) -> i64 { 102 | when! { 103 | n == 1 => 1, 104 | n % 2 == 0 => 2, 105 | is_prime(n) => n, 106 | else => { 107 | loop { 108 | let res = brent( 109 | n, 110 | random().next_bounds(2, n as u64 - 1) as i64, 111 | random().next_bounds(1, n as u64 - 1) as i64, 112 | ); 113 | if res != n { 114 | return res; 115 | } 116 | } 117 | }, 118 | } 119 | } 120 | --------------------------------------------------------------------------------