0% found this document useful (0 votes)
52 views19 pages

Memory Allocation and Data Structures Code

The document discusses various data structures and algorithms, including memory allocation, order statistics, and polynomial interpolation. It provides code snippets for implementing these concepts in C++, highlighting their functionalities and complexities. Key topics include disjoint-set structures, submatrix calculations, and efficient line containers.

Uploaded by

Med Mdeghri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views19 pages

Memory Allocation and Data Structures Code

The document discusses various data structures and algorithms, including memory allocation, order statistics, and polynomial interpolation. It provides code snippets for implementing these concepts in C++, highlighting their functionalities and complexities. Key topics include disjoint-set structures, submatrix calculations, and efficient line containers.

Uploaded by

Med Mdeghri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Memory allocate with support for finding the n’th el- for finding the n’th element, and

Running code with over 1GB mem- ement, and finding the index of an finding the index of an element. To
ory element. To get a map, change null get a map, change null type.
type. Time: O (log N)

# include < bits / stdc ++. h > # include < bits / extc ++. h >
// # pragma GCC optimize (" # include < bits / extc ++. h > using namespace
O3 , unroll - loops ") using namespace __gnu_pbds ;
// # pragma GCC target (" __gnu_pbds ; template < class T >
avx , avx2 , bmi , bmi2 , template < class T > using Tree = tree <T ,
popcnt , lzcnt ") using Tree = tree <T , null_type , less <T > ,
using namespace std ; null_type , less <T > , rb_tree_tag ,
void solve () {} rb_tree_tag , tree_order_statistics_node_
void main_ () { tree_order_statistics_node_update >;
ios_base :: >; void example () {
sync_with_stdio ( void example () { Tree < int > t , t2 ; t . insert
false ) ; Tree < int > t , t2 ; t . insert (8) ;
cin . tie (0) ; (8) ; auto it = t . insert (10) .
int t =1; auto it = t . insert (10) . first ;
cin >> t ; first ; assert ( it == t .
for ( int i = 1; i <= t ; assert ( it == t . lower_bound (9) ) ;
i ++) { lower_bound (9) ) ; assert ( t . order_of_key (10)
solve () ; assert ( t . order_of_key (10) == 1) ;
} == 1) ; assert ( t . order_of_key (11)
} assert ( t . order_of_key (11) == 2) ;
static void == 2) ; assert (* t . find_by_order
run_with_stack_size ( assert (* t . find_by_order (0) == 8) ;
void (* func ) ( void ) , (0) == 8) ; t . join ( t2 ) ; // assuming T
size_t stsize ) { t . join ( t2 ) ; // assuming T < T2 or T > T2 , merge
char * stack , * send ; < T2 or T > T2 , merge t2 into t
stack = ( char *) t2 into t }
malloc ( stsize ) ; }
send = stack + stsize UnionFindRollback.h
[Link] Disjoint-set data structure with
- 16;
Description undo. If undo is not needed, skip
send = ( char *) ((
uintptr_t ) send / st, time() and rollback(). Usage: int
16 * 16) ; # include < bits / stdc ++. h > t = [Link](); ...; [Link](t);
asm volatile ( using namespace std ;
" mov %% rsp , (%0) \ # define rep (i , a , b ) for (
n" int i = a ; i < ( b ) ; ++ struct RollbackUF {
" mov %0 , %% rsp \ n " i) vi e ; vector < pii > st ;
: # define all ( x ) begin ( x ) , RollbackUF ( int n ) : e (n ,
: " r " ( send ) ) ; end ( x ) -1) {}
func () ; # define sz ( x ) ( int ) ( x ) . int size ( int x ) { return
asm volatile ( " mov size () -e [ find ( x ) ]; }
(%0) , %% rsp \ n " : : typedef long long ll ; int find ( int x ) { return
" r " ( send ) ) ; typedef pair < int , int > e [ x ] < 0 ? x : find ( e [
free ( stack ) ; pii ; x ]) ; }
} typedef vector < int > vi ; int time () { return sz ( st
int main () { int main () { ); }
run_with_stack_size ( cin . tie (0) -> void rollback ( int t ) {
main_ , 1024 * 1024 sync_with_stdio (0) ; for ( int i = time () ; i
* 1024) ; // run cin . exceptions ( cin . --> t ;)
with a 1 GiB stack failbit ) ; e [ st [ i ]. first ] = st [ i ].
} } second ;
st . resize ( t ) ;
OrderStatisticTree.h OrderStatisticTree.h }
Description: A set (not multiset!) : A set (not multiset!) with support bool join ( int a , int b ) {
a = find ( a ) , b = find ( b ) ; } if (x - > k == y - > k ) x - > p =
if ( a == b ) return false ; vector <T > operator *( const x - > m > y - > m ? inf : -
if ( e [ a ] > e [ b ]) swap (a , vector <T >& vec ) const inf ;
b); { else x - > p = div (y - > m - x
st . push_back ({ a , e [ a ]}) ; vector <T > ret ( N ) ; - >m , x - > k - y - > k ) ;
st . push_back ({ b , e [ b ]}) ; rep (i ,0 , N ) rep (j ,0 , N ) ret return x - > p >= y - > p ;
e [ a ] += e [ b ]; e [ b ] = a ; [ i ] += d [ i ][ j ] * vec [ j }
return true ; ]; void add ( ll k , ll m ) {
} return ret ; auto z = insert ({ k , m ,
}; } 0}) , y = z ++ , x = y ;
} M operator ^( ll p ) const { while ( isect (y , z ) ) z =
assert ( p >= 0) ; erase ( z ) ;
SubMatrix.h M a , b (* this ) ; if ( x != begin () && isect
Calculate submatrix sums quickly, rep (i ,0 , N ) a . d [ i ][ i ] = 1; ( - -x , y ) ) isect (x , y =
given upper-left and lowerright cor- while ( p ) { erase ( y ) ) ;
ners (half-open). if ( p &1) a = a * b ; while (( y = x ) != begin ()
b = b*b; && ( - - x ) ->p >= y - > p )
p > >= 1; isect (x , erase ( y ) ) ;
} }
template < class T > return a ; ll query ( ll x ) {
struct SubMatrix { } assert (! empty () ) ;
vector < vector <T > > p ; }; auto l = * lower_bound ( x ) ;
SubMatrix ( vector < vector <T } return l . k * x + l . m ;
> >& v ) { }
int R = sz ( v ) , C = sz ( v LineContainer.h }
[0]) ; Container where you can add lines }
p . assign ( R +1 , vector <T >( C of the form kx+m, and query max-
+1) ) ; imum values at points x. Useful for Treap.h
rep (r ,0 , R ) rep (c ,0 , C ) dynamic programming (“convex hull A short self-balancing tree. It acts as
p [ r +1][ c +1] = v [ r ][ c ] + p trick”). a sequential container with log-time
[ r ][ c +1] + p [ r +1][ c ] - splits/joins, and is easy to augment
p [ r ][ c ]; with additional data.
}
T sum ( int u , int l , int d struct Line {
, int r ) { mutable ll k , m , p ;
return p [ d ][ r ] - p [ d ][ l ] bool operator <( const Line struct Node {
- p [ u ][ r ] + p [ u ][ l ]; & o ) const { return k Node * l = 0 , * r = 0;
} < o.k; } int val , y , c = 1;
}; bool operator <( ll x ) Node ( int val ) : val ( val ) ,
} const { return p < x ; y ( rand () ) {}
} void recalc () ;
Matrix.h }; };
Basic operations on square matrices struct LineContainer : int cnt ( Node * n ) { return
multiset < Line , less < > > n ? n - > c : 0; }
{ void Node :: recalc () { c =
// ( for doubles , use in cnt ( l ) + cnt ( r ) + 1;
template < class T , int N > f = 1/.0 , div ( a , b }
struct Matrix { ) = a/b) template < class F > void
typedef Matrix M ; static const ll inf = each ( Node * n , F f ) {
array < array <T , N > , N > d LLONG_MAX ; if ( n ) { each (n - >l , f ) ; f
{}; ll div ( ll a , ll b ) { // f (n - > val ) ; each (n - >r , f
M operator *( const M & m ) loored division ); }
const { return a / b - (( a ^ b ) < }
M a; 0 && a % b ) ; } pair < Node * , Node * > split (
rep (i ,0 , N ) rep (j ,0 , N ) bool isect ( iterator x , Node * n , int k ) {
rep (k ,0 , N ) a . d [ i ][ j ] += d iterator y ) { if (! n ) return {};
[ i ][ k ]* m . d [ k ][ j ]; if ( y == end () ) return x if ( cnt (n - > l ) >= k ) { //
return a ; - > p = inf , 0; n > va l >= k
for lower bound ( k ) x ) const { return ret ;
auto pa = split (n - >l , k ) ; double val = 0;
n - > l = pa . second ; for ( int i = sz ( a ) ; i - -;) }
n - > recalc () ; ( val *= x ) += a [ i ];
return { pa . first , n }; return val ; PolyInterpolate.
} else { } : Given n points (x[i], y[i]), com-
auto pa = split (n - >r , k - void diff () { putes an n-1-degree polynomial p
cnt (n - > l ) - 1) ; // rep (i ,1 , sz ( a ) ) a [i -1] = i that passes through them: p(x) =
and jus t k * a [ i ]; a[0] x 0 + ... + a[n 1] x n1 . For
n - > r = pa . first ; a . pop_back () ; numerical precision, pick x[k] = c
n - > recalc () ; } cos(k/(n 1) ), k = 0 . . . n 1
return {n , pa . second }; void divroot ( double x0 ) {
} double b = a . back () , c ; a
} . back () = 0; s
Node * merge ( Node * l , Node for ( int i = sz ( a ) -1; i - -;) typedef vector < double > vd
* r) { c = a[i], a[i] = a[i ;
if (! l ) return r ; +1]* x0 +b , b = c ; vd interpolate ( vd x , vd y
if (! r ) return l ; a . pop_back () ; , int n ) {
if (l - > y > r - > y ) { } vd res ( n ) , temp ( n ) ;
l - > r = merge (l - >r , r ) ; } rep (k ,0 ,n -1) rep (i , k +1 , n )
l - > recalc () ; } y [ i ] = ( y [ i ] - y [ k ]) / ( x
return l ; [ i ] - x [ k ]) ;
} else { PolyRoots.h double last = 0; temp [0]
r - > l = merge (l , r - > l ) ; Finds the real roots to a polynomial = 1;
r - > recalc () ; rep (k ,0 , n ) rep (i ,0 , n ) {
return r ; res [ i ] += y [ k ] * temp [ i ];
} swap ( last , temp [ i ]) ;
vector < double > polyRoots ( temp [ i ] -= last * x [ k ];
}
Poly p , double xmin , }
Node * ins ( Node * t , Node *
double xmax ) { return res ;
n , int pos ) {
if ( sz ( p . a ) == 2) {
auto pa = split (t , pos ) ;
return { - p . a [0]/ p . a BerlekampMasse
return merge ( merge ( pa .
[1]}; } on: Recovers any n-order linear re-
first , n ) , pa . second ) ;
vector < double > ret ; currence relation from the first 2n
}
Poly der = p ; terms of the recurrence. Useful
// Example application :
der . diff () ; for guessing linear recurrences after
move the range [ l , r
auto dr = polyRoots ( der , bruteforcing the first terms. Should
) to index k
xmin , xmax ) ; work on any field, but numerical sta-
void move ( Node *& t , int l
dr . push_back ( xmin -1) ; bility for floats is not guaranteed.
, int r , int k ) {
dr . push_back ( xmax +1) ; Output will have size n. Usage:
Node *a , *b , * c ;
sort ( all ( dr ) ) ; berlekampMassey(0, 1, 1, 3, 5, 11)
tie (a , b ) = split (t , l ) ;
rep (i ,0 , sz ( dr ) -1) { // 1,
tie (b , c ) = split (b , r
double l = dr [ i ] , h = dr [
- l);
i +1];
if ( k <= l ) t = merge ( ins
bool sign = p ( l ) > 0; es
(a , b , k ) , c ) ;
if ( sign ^ ( p ( h ) > 0) ) { vector < ll >
else t = merge (a , ins (c ,
rep ( it ,0 ,60) { // while ( berlekampMassey ( vector
b, k - r));
h l > 1 e 8 ) < ll > s ) {
double m = ( l + h ) / 2 , f int n = sz ( s ) , L = 0 , m =
}
= p(m); 0;
Polynomial. if (( f <= 0) ^ sign ) l = vector < ll > C ( n ) , B ( n ) , T ;
Description m; C [0] = B [0] = 1;
else h = m ; ll b = 1;
} rep (i ,0 , n ) { ++ m ;
ret . push_back (( l + h ) / ll d = s [ i ] % mod ;
struct Poly { 2) ; rep (j ,1 , L +1) d = ( d + C [ j
vector < double > a ; } ] * s [ i - j ]) % mod ;
double operator () ( double } if (! d ) continue ;
T = C ; ll coef = d *
modpow (b , mod -2) % mod double gss ( double a ,
double b , double (* f ) ( Integrate.h
;
double ) ) { Simple integration of a function over
rep (j ,m , n ) C [ j ] = ( C [ j ] -
double r = ( sqrt (5) -1) /2 , an interval using Simpson’s rule. The
coef * B [ j - m ]) %
eps = 1e -7; error should be proportional to h 4 ,
mod ;
double x1 = b - r *( b - a ) , although in practice you will want to
if (2 * L > i ) continue ;
x2 = a + r *( b - a ) ; verify that the result is stable to de-
L = i + 1 - L; B = T; b =
double f1 = f ( x1 ) , f2 = f sired precision when epsilon changes.
d ; m = 0;
} ( x2 ) ;
C . resize ( L + 1) ; C . erase ( while (b - a > eps )
template < class F >
C . begin () ) ; if ( f1 < f2 ) { // change
double quad ( double a ,
for ( ll & x : C ) x = ( mod to > to find maximum
double b , F f , const
- x ) % mod ; b = x2 ; x2 = x1 ; f2 = f1 ;
int n = 1000) {
return C ; x1 = b - r *( b - a ) ; f1 = f (
double h = ( b - a ) / 2 /
x1 ) ;
n, v = f(a) + f(b);
LinearRecurrenc } else {
rep (i ,1 , n *2)
on: Generates the k’th term of an a = x1 ; x1 = x2 ; f1 = f2 ;
v += f ( a + i * h ) * ( i &1 ?
n-order linear recurrence S[i] = P j x2 = a + r *( b - a ) ; f2 = f (
4 : 2) ;
S[i j 1]tr[j], given S[0 . . . n 1] and x2 ) ;
return v * h / 3;
tr[0 . . . n 1]. Faster than matrix }
}
multiplication. Useful together with return a ;
Berlekamp–Mass } IntegrateAdaptive.h
Fast integration using an adaptive
HillClimbing.h
Simpson’s rule.
nes : Poor man’s optimization for uni-
typedef vector < ll > Poly ; modal functions
ll linearRec ( Poly S , Poly typedef double d ;
tr , ll k ) { # define S (a , b ) ( f ( a ) + 4*
int n = sz ( tr ) ; typedef array < double , 2 >
P; f (( a + b ) / 2) + f ( b ) ) *
auto combine = [&]( Poly a (b - a ) / 6
, Poly b ) { template < class F > pair <
double , P > hillClimb ( P template < class F >
Poly res ( n * 2 + 1) ; d rec ( F & f , d a , d b , d
rep (i ,0 , n +1) rep (j ,0 , n +1) start , F f ) {
pair < double , P > cur ( f ( eps , d S ) {
res [ i + j ] = ( res [ i + j ] d c = ( a + b ) / 2;
+ a [ i ] * b [ j ]) % mod ; start ) , start ) ;
for ( double jmp = 1 e9 ; d S1 = S (a , c ) , S2 = S (c ,
for ( int i = 2 * n ; i > n b ) , T = S1 + S2 ;
; --i ) rep (j ,0 , n ) jmp > 1e -20; jmp /= 2)
{ if ( abs ( T - S ) <= 15 *
res [ i - 1 - j ] = ( res [ i - eps || b - a < 1e -10)
1 - j ] + res [ i ] * tr [ rep (j ,0 ,100) rep ( dx , -1 ,2)
rep ( dy , -1 ,2) { return T + ( T - S ) / 15;
j ]) % mod ; return rec (f , a , c , eps /
res . resize ( n + 1) ; P p = cur . second ;
p [0] += dx * jmp ; 2 , S1 ) + rec (f , c , b ,
return res ; eps / 2 , S2 ) ;
p [1] += dy * jmp ;
GoldenSectionSearch.h cur = min ( cur , make_pair ( }
Finds the argument minimizing the f(p), p)); template < class F >
function f in the interval [a, b] as- } d quad ( d a , d b , F f , d
suming f is unimodal on the interval, } eps = 1e -8) {
i.e. has only one local minimum. return cur ; return rec (f , a , b , eps ,
The maximum error in the result is } S (a , b ) ) ;
eps. Works equally well for maxi- }
mization with a small change in the Titre
Description Simplex.h
code. See TernarySearch.h in the Solves a general linear maximization
Various chapter for a discrete ver- problem: maximize c T x subject to
sion. Usage: double func(double x) # include < bits / stdc ++. h > Ax b, x 0. Returns -inf if there is
return 4+x+.3*x*x; double xmin = int main () { no solution, inf if there are arbitrar-
gss(-1000,1000,func); cout < <1 < < endl ; ily good solutions, or the maximum
} value of c T x otherwise. The in-
put vector is set to an optimal x (or D [ i ][ s ] *= - inv ; double > >& a ) {
in the unbounded case, an arbitrary D [ r ][ s ] = inv ; int n = sz ( a ) ; double res
solution fulfilling the constraints). swap ( B [ r ] , N [ s ]) ; = 1;
Numerical stability is not guaran- } rep (i ,0 , n ) {
teed. For better performance, define bool simplex ( int phase ) { int b = i ;
variables such that x = 0 is viable. int x = m + phase - 1; rep (j , i +1 , n ) if ( fabs ( a [ j
Usage: vvd A = 1,-1, -1,1, -1,-2; vd for (;;) { ][ i ]) > fabs ( a [ b ][ i ]) )
b = 1,1,-4, c = -1,-1, x; T val = int s = -1; b = j;
LPSolver(A, b, c).solve(x); rep (j ,0 , n +1) if ( N [ j ] != if ( i != b ) swap ( a [ i ] , a [
- phase ) ltj ( D [ x ]) ; b ]) , res *= -1;
if ( D [ x ][ s ] >= - eps ) res *= a [ i ][ i ];
return true ; if ( res == 0) return 0;
typedef double T ; // long
int r = -1; rep (j , i +1 , n ) {
double , Rational ,
rep (i ,0 , m ) { double v = a [ j ][ i ] / a [ i
double + mod <P >...
if ( D [ i ][ s ] <= eps ) ][ i ];
typedef vector <T > vd ;
continue ; if ( v != 0) rep (k , i +1 , n )
typedef vector < vd > vvd ;
if ( r == -1 || MP ( D [ i ][ n a [ j ][ k ] -= v * a [ i ][ k
const T eps = 1e -8 , inf =
+1] / D [ i ][ s ] , B [ i ]) ];
1/.0;
< MP ( D [ r ][ n +1] / D [ r ][ s ] , }
# define MP make_pair
B [ r ]) ) r = i ; }
# define ltj ( X ) if ( s == -1
} return res ;
|| MP ( X [ j ] , N [ j ]) < MP
if ( r == -1) return false
( X [ s ] , N [ s ]) ) s = j IntDeterminant.h
;
struct LPSolver { Calculates determinant using modu-
pivot (r , s ) ;
int m , n ; lar arithmetics. Modulos can also be
}
vi N , B ; removed to get a pure-integer ver-
}
vvd D ; sion.
T solve ( vd & x ) {
LPSolver ( const vvd & A ,
int r = 0;
const vd & b , const vd &
rep (i ,1 , m ) if ( D [ i ][ n +1]
c) : const ll mod = 12345;
< D [ r ][ n +1]) r = i ;
m ( sz ( b ) ) , n ( sz ( c ) ) , N ( n ll det ( vector < vector < ll
if ( D [ r ][ n +1] < - eps ) {
+1) , B ( m ) , D ( m +2 , vd ( n > >& a ) {
pivot (r , n ) ;
+2) ) { int n = sz ( a ) ; ll ans =
if (! simplex (2) || D [ m
rep (i ,0 , m ) rep (j ,0 , n ) D [ i 1;
+1][ n +1] < - eps )
][ j ] = A [ i ][ j ]; rep (i ,0 , n ) {
return - inf ;
rep (i ,0 , m ) { B [ i ] = n + i ; rep (j , i +1 , n ) {
rep (i ,0 , m ) if ( B [ i ] ==
D [ i ][ n ] = -1; D [ i ][ n while ( a [ j ][ i ] != 0) { //
-1) {
+1] = b [ i ];} gcd step
int s = 0;
rep (j ,0 , n ) { N [ j ] = j ; D [ ll t = a [ i ][ i ] / a [ j ][ i ];
rep (j ,1 , n +1) ltj ( D [ i ]) ;
m ][ j ] = -c [ j ]; } if ( t ) rep (k ,i , n )
pivot (i , s ) ;
N [ n ] = -1; D [ m +1][ n ] = 1; a [ i ][ k ] = ( a [ i ][ k ] - a [ j
}
} ][ k ] * t ) % mod ;
}
void pivot ( int r , int s ) swap ( a [ i ] , a [ j ]) ;
bool ok = simplex (1) ; x =
{ ans *= -1;
vd ( n ) ;
T * a = D [ r ]. data () , inv = }
rep (i ,0 , m ) if ( B [ i ] < n )
1 / a [ s ]; }
x [ B [ i ]] = D [ i ][ n +1];
rep (i ,0 , m +2) if ( i != r ans = ans * a [ i ][ i ] % mod
return ok ? D [ m ][ n +1] :
&& abs ( D [ i ][ s ]) > eps ) ;
inf ;
{ if (! ans ) return 0;
}
T * b = D [ i ]. data () , inv2 }
};
= b [ s ] * inv ; return ( ans + mod ) % mod ;
rep (j ,0 , n +2) b [ j ] -= a [ j ] Determinant.h }
* inv2 ; Calculates determinant of a matrix.
b [ s ] = a [ s ] * inv2 ; Destroys the matrix. SolveLinear.h
} Solves A x = b. If there are mul-
rep (j ,0 , n +2) if ( j != s ) tiple solutions, an arbitrary one is
D [ r ][ j ] *= inv ; returned. Returns rank, or -1 if no
rep (i ,0 , m +2) if ( i != r ) double det ( vector < vector < solutions. Data in A and b is lost.
for ( int i = rank ; i - -;)
rep (j ,0 , n ) if ( j != i ) // {
instead of rep ( j , i if (! b [ i ]) continue ;
typedef vector < double > vd
+1 , n ) x [ col [ i ]] = 1;
;
// . . . then at the end rep (j ,0 , i ) b [ j ] ^= A [ j ][ i
const double eps = 1e -12;
: ];
int solveLinear ( vector < vd
x . assign (m , undefined ) ; }
>& A , vd & b , vd & x ) {
rep (i ,0 , rank ) { return rank ; // ( multiple
int n = sz ( A ) , m = sz ( x ) ,
rep (j , rank , m ) if ( fabs ( A [ so lutions i f rank <
rank = 0 , br , bc ;
i ][ j ]) > eps ) goto m)
if ( n ) assert ( sz ( A [0]) ==
fail ;
m); MatrixInverse.
x [ col [ i ]] = b [ i ] / A [ i ][ i
vi col ( m ) ; iota ( all ( col ) , : Invert matrix A. Returns rank; re-
];
0) ; sult is stored in A unless singular
fail :;
rep (i ,0 , n ) { (rank ¡ n). Can easily be extended
double v , bv = 0; SolveLinearBinary.h to prime moduli; for prime powers,
rep (r ,i , n ) rep (c ,i , m ) Solves Ax = b over F2. If there are repeatedly set A 1 = A 1 (2I AA1 )
if (( v = fabs ( A [ r ][ c ]) ) > multiple solutions, one is returned (mod p k ) where A 1 starts as the
bv ) arbitrarily. Returns rank, or -1 if no inverse of A mod p, and k is doubled
br = r , bc = c , bv = v ; solutions. Destroys A and b. in each step. Time: O n 3
if ( bv <= eps ) {
rep (j ,i , n ) if ( fabs ( b [ j ])
> eps ) return -1; s
break ; typedef bitset <1000 > bs ; int matInv ( vector < vector <
} int solveLinear ( vector < bs double > >& A ) {
swap ( A [ i ] , A [ br ]) ; >& A , vi & b , bs & x , int n = sz ( A ) ; vi col ( n ) ;
swap ( b [ i ] , b [ br ]) ; int m ) { vector < vector < double > >
swap ( col [ i ] , col [ bc ]) ; int n = sz ( A ) , rank = 0 , tmp (n , vector < double >(
rep (j ,0 , n ) swap ( A [ j ][ i ] , br ; n));
A [ j ][ bc ]) ; assert ( m <= sz ( x ) ) ; rep (i ,0 , n ) tmp [ i ][ i ] = 1 ,
bv = 1/ A [ i ][ i ]; vi col ( m ) ; iota ( all ( col ) , col [ i ] = i ;
rep (j , i +1 , n ) { 0) ; rep (i ,0 , n ) {
double fac = A [ j ][ i ] * bv rep (i ,0 , n ) { int r = i , c = i ;
; for ( br = i ; br < n ; ++ br ) if rep (j ,i , n ) rep (k ,i , n )
b [ j ] -= fac * b [ i ]; ( A [ br ]. any () ) break ; if ( fabs ( A [ j ][ k ]) > fabs (
rep (k , i +1 , m ) A [ j ][ k ] -= if ( br == n ) { A [ r ][ c ]) )
fac * A [ i ][ k ]; rep (j ,i , n ) if ( b [ j ]) r = j, c = k;
} return -1; if ( fabs ( A [ r ][ c ]) < 1e
rank ++; break ; -12) return i ;
} } A [ i ]. swap ( A [ r ]) ; tmp [ i ].
x . assign (m , 0) ; int bc = ( int ) A [ br ]. swap ( tmp [ r ]) ;
for ( int i = rank ; i - -;) _Find_next (i -1) ; rep (j ,0 , n )
{ swap ( A [ i ] , A [ br ]) ; swap ( A [ j ][ i ] , A [ j ][ c ]) ,
b [ i ] /= A [ i ][ i ]; swap ( b [ i ] , b [ br ]) ; swap ( tmp [ j ][ i ] , tmp [ j
x [ col [ i ]] = b [ i ]; swap ( col [ i ] , col [ bc ]) ; ][ c ]) ;
rep (j ,0 , i ) b [ j ] -= A [ j ][ irep (j ,0 , n ) if ( A [ j ][ i ] != swap ( col [ i ] , col [ c ]) ;
] * b [ i ]; A [ j ][ bc ]) { double v = A [ i ][ i ];
} A [ j ]. flip ( i ) ; A [ j ]. flip ( rep (j , i +1 , n ) {
return rank ; // ( multiple bc ) ; double f = A [ j ][ i ] / v ;
so lutions i f rank < } A [ j ][ i ] = 0;
m) rep (j , i +1 , n ) if ( A [ j ][ i ]) rep (k , i +1 , n ) A [ j ][ k ] -= f
{ * A [ i ][ k ];
SolveLinear2.h b [ j ] ^= b [ i ]; rep (k ,0 , n ) tmp [ j ][ k ] -= f
To get all uniquely determined val- A [ j ] ^= A [ i ]; * tmp [ i ][ k ];
ues of x back from SolveLinear, make } }
the following changes rank ++; rep (j , i +1 , n ) A [ i ][ j ] /= v
} ;
x = bs () ; rep (j ,0 , n ) tmp [ i ][ j ] /= v
; ]]) ; outs ( n ) , outl ( n ) ;
A [ i ][ i ] = 1; for ( int k = 1; k < n ; k rep (i ,0 , sz ( a ) ) L [ i ] = C ((
} *= 2) int ) a [ i ] / cut , ( int ) a
for ( int i = n -1; i > 0; for ( int i = 0; i < n ; i [ i ] % cut ) ;
--i ) rep (j ,0 , i ) { += 2 * k ) rep (j ,0 , k ) { rep (i ,0 , sz ( b ) ) R [ i ] = C ((
double v = A [ j ][ i ]; C z = rt [ j + k ] * a [ i + j + k ]; int ) b [ i ] / cut , ( int ) b
rep (k ,0 , n ) tmp [ j ][ k ] -= v // (25% fas te r i f [ i ] % cut ) ;
* tmp [ i ][ k ]; h a n d ro l led ) fft ( L ) , fft ( R ) ;
} a[i + j + k] = a[i + j] - rep (i ,0 , n ) {
rep (i ,0 , n ) rep (j ,0 , n ) A [ z; int j = -i & ( n - 1) ;
col [ i ]][ col [ j ]] = tmp [ a [ i + j ] += z ; outl [ j ] = ( L [ i ] + conj ( L [
i ][ j ]; } j ]) ) * R [ i ] / (2.0 * n
return n ; } );
vd conv ( const vd & a , outs [ j ] = ( L [ i ] - conj ( L [
FastFourierTransform.h const vd & b ) { j ]) ) * R [ i ] / (2.0 * n
fft(a) computes fˆ(k) = P x a[x] if ( a . empty () || b . empty ) / 1i;
exp(2i · kx/N) for all k. N must () ) return {}; }
be a power of 2. Useful for convo- vd res ( sz ( a ) + sz ( b ) - 1) fft ( outl ) , fft ( outs ) ;
lution: conv(a, b) = c, where c[x] ; rep (i ,0 , sz ( res ) ) {
= Pa[i]b[x i]. For convolution of int L = 32 - ll av = ll ( real ( outl [ i ])
complex numbers or more than two __builtin_clz ( sz ( res ) ) +.5) , cv = ll ( imag (
vectors: FFT, multiply pointwise, , n = 1 << L ; outs [ i ]) +.5) ;
divide by n, reverse(start+1, end), vector <C > in ( n ) , out ( n ) ; ll bv = ll ( imag ( outl [ i ])
FFT back. Rounding is safe if (Pa copy ( all ( a ) , begin ( in ) ) ; +.5) + ll ( real ( outs [ i
2 i + Pb 2 i ) log2 N ¡ 9 · 1014 (in rep (i ,0 , sz ( b ) ) in [ i ]. imag ]) +.5) ;
practice 1016 ; higher for random ( b [ i ]) ; res [ i ] = (( av % M * cut +
inputs). Otherwise, use NTT/FFT- fft ( in ) ; bv ) % M * cut + cv ) %
Mod for ( C & x : in ) x *= x ; M;
rep (i ,0 , n ) out [ i ] = in [ - i }
& ( n - 1) ] - conj ( in [ return res ;
typedef complex < double > C
i ]) ; }
;
fft ( out ) ;
typedef vector < double > vd NumberTheoreticTransform.h
rep (i ,0 , sz ( res ) ) res [ i ] =
; ntt(a) computes fˆ(k) = P x a[x]g xk
imag ( out [ i ]) / (4 * n
void fft ( vector <C >& a ) { for all k, where g = root(mod1)/N . N
);
int n = sz ( a ) , L = 31 - must be a power of 2. Useful for con-
return res ;
__builtin_clz ( n ) ; volution modulo specific nice primes
}
static vector < complex < of the form 2a b + 1, where the con-
long double > > R (2 , 1) ; FastFourierTransformMod.h volution result has size at most 2a .
static vector <C > rt (2 , 1) Higher precision FFT, can be used For arbitrary modulo, see FFTMod.
; // (^ 10% fas te r i for convolutions modulo arbitrary in- conv(a, b) = c, where c[x] = Pa[i]b[x
f double ) tegers as long as N log2 N · mod ¡ 8.6 i]. For manual convolution: NTT the
for ( static int k = 2; k · 1014 (in practice 1016 or higher). inputs, multiply pointwise, divide by
< n ; k *= 2) { Inputs must be in [0, mod). n, reverse(start+1, end), NTT back.
R . resize ( n ) ; rt . resize ( n ) Inputs must be in [0, mod).
;
auto x = polar (1.0 L , acos typedef vector < ll > vl ;
( -1.0 L ) / k ) ; template < int M > vl const ll mod = (119 <<
rep (i ,k ,2* k ) rt [ i ] = R [ i ] convMod ( const vl &a , 23) + 1 , root = 62; //
= i &1 ? R [ i /2] * x : const vl & b ) { = 998244353
R [ i /2]; if ( a . empty () || b . empty // For p < 2^30 there is
} () ) return {}; a lso e . g . 5 << 25 ,
vi rev ( n ) ; vl res ( sz ( a ) + sz ( b ) - 1) 7 << 26 , 479 << 21
rep (i ,0 , n ) rev [ i ] = ( rev [ ; // and 483 << 21 ( same
i / 2] | ( i & 1) << L ) int B =32 - __builtin_clz ( sz root ) . The l as t two
/ 2; ( res ) ) , n =1 < <B , cut = are > 10^9.
rep (i ,0 , n ) if ( i < rev [ i int ( sqrt ( M ) ) ; typedef vector < ll > vl ;
]) swap ( a [ i ] , a [ rev [ i vector <C > L ( n ) , R ( n ) , void ntt ( vl & a ) {
int n = sz ( a ) , L = 31 - Transform to a basis with fast con- ll modLog ( ll a , ll b , ll
__builtin_clz ( n ) ; volutions of the form c[z] = X z=xy m) {
static vl rt (2 , 1) ; a[x] · b[y], where is one of AND, ll n = ( ll ) sqrt ( m ) + 1 ,
for ( static int k = 2 , s OR, XOR. The size of a must be a e = 1 , f = 1 , j = 1;
= 2; k < n ; k *= 2 , s power of two. unordered_map < ll , ll > A ;
++) { while ( j <= n && ( e = f =
rt . resize ( n ) ; e * a % m ) != b % m )
ll z [] = {1 , modpow ( root , void FST ( vi & a , bool inv ) A [ e * b % m ] = j ++;
mod >> s ) }; { if ( e == b % m ) return j ;
rep (i ,k ,2* k ) rt [ i ] = rt [ i for ( int n = sz ( a ) , step if ( __gcd (m , e ) == __gcd (
/ 2] * z [ i & 1] % mod = 1; step < n ; step *= m, b))
; 2) { rep (i ,2 , n +2) if ( A . count (
} for ( int i = 0; i < n ; i e = e * f % m)
vi rev ( n ) ; += 2 * step ) rep (j ,i , i return n * i - A [ e ];
rep (i ,0 , n ) rev [ i ] = ( rev [ + step ) { return -1;
i / 2] | ( i & 1) << L ) int & u = a [ j ] , & v = a [ j + }
/ 2; step ]; tie (u , v ) =
rep (i ,0 , n ) if ( i < rev [ i inv ? pii ( v - u , u ) : pii ModSum.h
]) swap ( a [ i ] , a [ rev [ i (v , u + v ) ; // AND Sums of mod’ed arithmetic progres-
]]) ; inv ? pii (v , u - v ) : pii sions. modsum(to, c, k, m) = Pto1
for ( int k = 1; k < n ; k ( u + v , u ) ; // OR i=0 (ki + c)floored division
*= 2) pii ( u + v , u - v ) ; // XOR
for ( int i = 0; i < n ; i }
+= 2 * k ) rep (j ,0 , k ) { } typedef unsigned long
ll z = rt [ j + k ] * a [ i + if ( inv ) for ( int & x : a ) long ull ;
j + k ] % mod , & ai = a [ x /= sz ( a ) ; // XOR ull sumsq ( ull to ) {
i + j ]; only return to / 2 * (( to
a [ i + j + k ] = ai - z + ( } -1) | 1) ; }
z > ai ? mod : 0) ; vi conv ( vi a , vi b ) { ull divsum ( ull to , ull c ,
ai += ( ai + z >= mod ? z FST (a , 0) ; FST (b , 0) ; ull k , ull m ) {
- mod : z ) ; rep (i ,0 , sz ( a ) ) a [ i ] *= b [ ull res = k / m * sumsq (
} i ]; to ) + c / m * to ;
} FST (a , 1) ; return a ; k %= m ; c %= m ;
vl conv ( const vl &a , } if (! k ) return res ;
const vl & b ) { ull to2 = ( to * k + c ) /
if ( a . empty () || b . empty ModInverse.h m;
() ) return {}; Pre-computation of modular in- return res + ( to - 1) *
int s = sz ( a ) + sz ( b ) - verses. Assumes LIM mod and that to2 - divsum ( to2 , m -1
1 , B = 32 - mod is a prime. - c, m, k);
__builtin_clz ( s ) , n = }
1 ll modsum ( ull to , ll c ,
<< B ; const ll mod = ll k , ll m ) {
int inv = modpow (n , mod - 1000000007 , LIM = c = (( c % m ) + m ) % m ;
2) ; 200000; k = (( k % m ) + m ) % m ;
vl L ( a ) , R ( b ) , out ( n ) ; ll * inv = new ll [ LIM ] - return to * c + k * sumsq
L . resize ( n ) , R . resize ( n ) ; 1; inv [1] = 1; ( to ) - m * divsum ( to ,
ntt ( L ) , ntt ( R ) ; rep (i ,2 , LIM ) inv [ i ] = mod c, k, m);
rep (i ,0 , n ) out [ - i & ( n - - ( mod / i ) * inv [ mod }
1) ] = ( ll ) L [ i ] * R [ i ] % i ] % mod ;
% mod * inv % ModMulLL.h
ModLog.h Calculate a·b mod c (or a b mod c)
mod ;
Returns the smallest x ¿ 0 s.t. a x = for 0 a, b c 7.2·1018 .
ntt ( out ) ;
b (mod m), or 1 if no such x exists.
return { out . begin () , out .
modLog(a,1,m) can be used to cal-
begin () + s };
culate the order of a. typedef unsigned long
}
long ull ;
ull modmul ( ull a , ull b ,
FastSubsetTransform.h ull M ) {
ll ret = a * b - M * ull b = b * g % p; }
(1. L / M * a * b ) ; } vector < ull > factor ( ull n )
return ret + M * ( ret < {
0) - M * ( ret >= ( ll ) M MillerRabin. if ( n == 1) return {};
); Deterministic Miller-Rabin primal- if ( isPrime ( n ) ) return { n
} ity test. Guaranteed to work for };
ull modpow ( ull b , ull e , numbers up to 7 · 1018; for larger ull x = pollard ( n ) ;
ull mod ) { numbers, use Python and extend A auto l = factor ( x ) , r =
ull ans = 1; randomly factor ( n / x ) ;
for (; e ; b = modmul (b , b l . insert ( l . end () , all ( r ) )
, mod ) , e /= 2) ;
if ( e & 1) ans = modmul ( return l ;
ans , b , mod ) ; bool isPrime ( ull n ) {
return ans ; if ( n < 2 || n % 6 % 4 != euclid.
} 1) return ( n | 1) == Finds two integers x and y, such that
3; ax + by = gcd(a, b). If you just need
ModSqrt.h ull A [] = {2 , 325 , 9375 , gcd, use the built in gcd instead. If
Tonelli-Shanks algorithm for modu- 28178 , 450775 , a and b are coprime, then x is the
lar square roots. Finds x s.t. x 2 = a 9780504 , 1795265022} , inverse of a (mod b).
(mod p) (x gives the other solution). s = __builtin_ctzll (n -1) ,
Time: O d = n >> s ;
log2 p worst case, O (log p) for for ( ull a : A ) { // ^
most count t ra i l in g ll euclid ( ll a , ll b , ll
zeroes &x , ll & y ) {
ull p = modpow ( a %n , d , n ) if (! b ) return x = 1 , y =
, i = s; 0, a;
ll sqrt ( ll a , ll p ) { while ( p != 1 && p != n - ll d = euclid (b , a % b , y
a %= p ; if ( a < 0) a += p 1 && a % n && i - -) , x);
; p = modmul (p , p , n ) ; return y -= a / b * x , d ;
if ( a == 0) return 0; if ( p != n -1 && i != s )
assert ( modpow (a , (p -1) /2 , return 0; }
p ) == 1) ; // e lse no }
so lution CRT.
return 1; : Chinese Remainder Theorem.
if ( p % 4 == 3) return
modpow (a , ( p +1) /4 , p ) ; crt(a, m, b, n) computes x such
Factor.h
// a ^( n +3) /8 or 2^( n +3) /8 that x a (mod m), x b (mod n). If
Pollard-rho randomized factorization
2^( n 1 ) /4 works —a— ¡ m and —b— ¡ n, x will obey
algorithm. Returns prime factors of
i f p % 8 == 5 0 x ¡ lcm(m, n). Assumes mn ¡ 2 62 .
a number, in arbitrary order (e.g.
ll s = p - 1 , n = 2; 2299 -¿ 11, 19, 11).
int r = 0 , m ;
while ( s % 2 == 0) ll crt ( ll a , ll m , ll b ,
++ r , s /= 2; ll n ) {
while ( modpow (n , ( p - 1) ull pollard ( ull n ) { if ( n > m ) swap (a , b ) ,
/ 2 , p ) != p - 1) ++ n ; auto f = [ n ]( ull x ) { swap (m , n ) ;
ll x = modpow (a , ( s + 1) return modmul (x , x , n ) ll x , y , g = euclid (m , n ,
/ 2, p); + 1; }; x, y);
ll b = modpow (a , s , p ) , g ull x = 0 , y = 0 , t = 30 , assert (( a - b ) % g == 0) ;
= modpow (n , s , p ) ; prd = 2 , i = 1 , q ; // e lse no so lution
for (;; r = m ) { while ( t ++ % 40 || __gcd ( x = (b - a) % n * x % n /
ll t = b ; prd , n ) == 1) { g * m + a;
for ( m = 0; m < r && t != if ( x == y ) x = ++ i , y = return x < 0 ? x + m * n / g
1; ++ m ) f(x); : x;
t = t * t % p; if (( q = modmul ( prd , max (
if ( m == 0) return x ; x , y ) - min (x , y ) , n ) ) ) phiFunction.
ll gs = modpow (g , 1 LL << prd = q ; Euler’s function is defined as (n)
( r - m - 1) , p ) ; x = f(x), y = f(f(y)); := of positive integers n that are
g = gs * gs % p ; } coprime with n. (1) = 1, p prime (p
x = x * gs % p ; return __gcd ( prd , n ) ; k ) = (p 1)p k1 , m, n coprime (mn)
= (m)(n). If n = p k1 1 p k2 2 ...pkr approximation .
r then (n) = (p1 1)p k11 1 ...(pr 1)p return ( abs ( x - ( d ) NP / (
IntPerm.h
kr1 r . (n) = n · Q p—n (1 1/p). P d ) NQ ) < abs ( x - ( d ) P /
Permutation -¿ integer conversion.
d—n (d) = n, P 1kn,gcd(k,n)=1 k = (d)Q)) ?
(Not order preserving.) Integer -¿
n(n)/2, n ¿ 1 make_pair ( NP , NQ ) :
permutation can use a lookup table.
make_pair (P , Q ) ;
}
if ( abs ( y = 1/( y - ( d ) a ) ) int permToInt ( vi & v ) {
const int LIM = 5000000; > 3* N ) { int use = 0 , i = 0 , r =
int phi [ LIM ]; return { NP , NQ }; 0;
void calculatePhi () { } for ( int x : v ) r = r * ++ i
rep (i ,0 , LIM ) phi [ i ] = i &1 LP = P ; P = NP ;
+ __builtin_popcount (
? i : i /2; LQ = Q ; Q = NQ ; use & -(1 < < x ) ) ,
for ( int i = 3; i < LIM ; } use |= 1 << x ; // ( note :
i += 2) if ( phi [ i ] == i }
minus , not !)
)
return r ;
for ( int j = i ; j < LIM ; FracBinarySearch.h
}
j += i ) phi [ j ] -= phi [ Given f and N, finds the smallest
j] / i; fraction p/q [0, 1] such that f(p/q) multinomial
is true, and p, q N. You may want to : Computes k1 + · · · + kn k1, k2, .
ContinuedFractions.h throw an exception from f if it finds . . , kn = ( Pki)! k1!k2!...kn!
Given N and a real number x 0, an exact solution, in which case N
finds the closest rational approxima- can be removed.
tion p/q with p, q N. It will obey
—p/q x— 1/qN. For consecutive ll multinomial ( vi & v ) {
convergents, pk+1qk qk+1pk = (1)k struct Frac { ll p , q ; }; ll c = 1 , m = v . empty () ?
. (pk/qk alternates between ¿ x and template < class F > 1 : v [0];
¡ x.) If x is rational, y eventually Frac fracBS ( F f , ll N ) { rep (i ,1 , sz ( v ) ) rep (j ,0 , v [
becomes ; if x is the root of a degree bool dir = 1 , A = 1 , B = i ])
2 polynomial the a’s eventually be- 1;
c = c * ++ m / ( j +1) ;
come cyclic. Frac lo {0 , 1} , hi {1 , 1};
return c ;
// Set hi to 1/0 to
search (0 , N ] BellmanFord
typedef double d ; // for if ( f ( lo ) ) return lo ; : Calculates shortest paths from s
N 1 e7 ; long assert ( f ( hi ) ) ; in a graph that might have negative
double for N 1 e9 while ( A || B ) { edge weights. Unreachable nodes get
pair < ll , ll > approximate ( ll adv = 0 , step = 1; // dist = inf; nodes reachable through
d x , ll N ) { move hi i f dir , e negative-weight cycles get dist = -
ll LP = 0 , LQ = 1 , P = 1 , lse lo inf. Assumes V 2 max —wi— ¡ 2 63
Q = 0 , inf = for ( int si = 0; step ; (
LLONG_MAX ; d y = x ; step *= 2) > >= si ) {
for (;;) { adv += step ;
ll lim = min ( P ? (N - LP ) / Frac mid { lo . p * adv + hi . const ll inf = LLONG_MAX ;
P : inf , Q ? (N - LQ ) / p , lo . q * adv + hi . q }; struct Ed { int a , b , w ,
Q : inf ) , if ( abs ( mid . p ) > N || mid s () { return a < b ? a
a = ( ll ) floor ( y ) , b = min . q > N || dir == ! f ( : -a ; }};
(a , lim ) , mid ) ) { struct Node { ll dist =
NP = b * P + LP , NQ = b * Q + adv -= step ; si = 2; inf ; int prev = -1; };
LQ ; } void bellmanFord ( vector <
if ( a > b ) { } Node >& nodes , vector <
// I f b > a /2 , we have a hi . p += lo . p * adv ; Ed >& eds , int s ) {
s e m i convergent hi . q += lo . q * adv ; nodes [ s ]. dist = 0;
that gives us a dir = ! dir ; sort ( all ( eds ) , []( Ed a ,
// better approximation ; swap ( lo , hi ) ; Ed b ) { return a . s () <
i f b = a /2 , we A = B ; B = !! adv ; b . s () ; }) ;
may have one . } int lim = sz ( nodes ) / 2 +
// Return {P , Q } here for return dir ? hi : lo ; 2; // /3+100 with shu
a more canonical } f f led vert ices
rep (i ,0 , lim ) for ( Ed ed : ing of vertices, such that there are for ( auto e : graph [ x ]) {
eds ) { edges only from left to right. If there if ( par [ e . first ] == -1 &&
Node cur = nodes [ ed . a ] , & are cycles, the returned list will have e . second > 0) {
dest = nodes [ ed . b ]; size smaller than n – nodes reachable par [ e . first ] = x ;
if ( abs ( cur . dist ) == inf ) from cycles will not be returne q [ ptr ++] = e . first ;
continue ; if ( e . first == sink ) goto
ll d = cur . dist + ed . w ; out ;
if ( d < dest . dist ) { s }
dest . prev = ed . a ; vi topoSort ( const vector < }
dest . dist = ( i < lim -1 ? vi >& gr ) { }
d : - inf ) ; vi indeg ( sz ( gr ) ) , ret ; return flow ;
} for ( auto & li : gr ) for ( out :
} int x : li ) indeg [ x T inc = numeric_limits <T
rep (i ,0 , lim ) for ( Ed e : ]++; >:: max () ;
eds ) { queue < int > q ; // use for ( int y = sink ; y !=
if ( nodes [ e . a ]. dist == - priority queue for l e source ; y = par [ y ])
inf ) x i c . la rges t ans inc = min ( inc , graph [ par [
nodes [ e . b ]. dist = - inf ; . y ]][ y ]) ;
} rep (i ,0 , sz ( gr ) ) if ( indeg flow += inc ;
[ i ] == 0) q . push ( i ) ; for ( int y = sink ; y !=
FloydWarshall while (! q . empty () ) { source ; y = par [ y ]) {
: Calculates all-pairs shortest path int i = q . front () ; // top int p = par [ y ];
in a directed graph that might have () for pr ior ity if (( graph [ p ][ y ] -= inc )
negative edge weights. Input is an queue <= 0) graph [ p ]. erase ( y
distance matrix m, where m[i][j] = ret . push_back ( i ) ; );
inf if i and j are not adjacent. As q . pop () ; graph [ y ][ p ] += inc ;
output, m[i][j] is set to the shortest for ( int x : gr [ i ]) }
distance between i and j, inf if no if ( - - indeg [ x ] == 0) q . }
path, or -inf if the path goes through push ( x ) ;
a negative-weight cycl } MinCut.h
return ret ; After running max-flow, the left side
of a min-cut from s to t is given by
s EdmondsKarp. all vertices reachable from s, only
const ll inf = 1 LL << 62; Flow algorithm with guaranteed traversing edges with positive resid-
void floydWarshall ( vector complexity O(V E2 ). To get edge ual capacity.
< vector < ll > >& m ) { flow values, compare capacities be-
int n = sz ( m ) ; fore and after, and take the positive
rep (i ,0 , n ) m [ i ][ i ] = min ( values only. # include < bits / stdc ++. h >
m [ i ][ i ] , 0 LL ) ; int main () {
rep (k ,0 , n ) rep (i ,0 , n ) rep cout < <1 < < endl ;
(j ,0 , n ) }
if ( m [ i ][ k ] != inf && m [ k template < class T > T
][ j ] != inf ) { edmondsKarp ( vector < GlobalMinCut.h
auto newDist = max ( m [ i ][ k unordered_map < int , T : Find a global minimum cut in an
] + m [ k ][ j ] , - inf ) ; > >& undirected graph, as represented by
m [ i ][ j ] = min ( m [ i ][ j ] , graph , int source , int an adjacency matrix
newDist ) ; sink ) {
} assert ( source != sink ) ;
rep (k ,0 , n ) if ( m [ k ][ k ] < T flow = 0;
0) rep (i ,0 , n ) rep (j ,0 , vi par ( sz ( graph ) ) , q = pair < int , vi >
n) par ; globalMinCut ( vector < vi
if ( m [ i ][ k ] != inf && m [ k for (;;) { > mat ) {
][ j ] != inf ) m [ i ][ j ] = fill ( all ( par ) , -1) ; pair < int , vi > best = {
- inf ; par [ source ] = 0; INT_MAX , {}};
int ptr = 1; int n = sz ( mat ) ;
TopoSor q [0] = source ; vector < vi > co ( n ) ;
n: Topological sorting. Given is an rep (i ,0 , ptr ) { rep (i ,0 , n ) co [ i ] = { i };
oriented graph. Output is an order- int x = q [ i ]; rep ( ph ,1 , n ) {
vi w = mat [0]; Graph g should be a list of neighbors vi q , cover ;
size_t s = 0 , t = of the left partition, and btoa should rep (i ,0 , n ) if ( lfound [ i ])
rep ( it ,0 ,n - ph ) { // O ( V be a vector full of -1’s of the same q . push_back ( i ) ;
^2) > O ( E log V ) size as the right partition. Returns while (! q . empty () ) {
with prio . queue the size of the matching. btoa[i] will int i = q . back () ; q .
w [ t ] = INT_MIN ; be the match for vertex i on the right pop_back () ;
s = t , t = max_element ( side, or 1 if it’s not matched. lfound [ i ] = 1;
all ( w ) ) - w . begin () ; for ( int e : g [ i ]) if (!
rep (i ,0 , n ) w [ i ] += mat [ t seen [ e ] && match [ e ] !=
][ i ]; bool find ( int j , vector < -1) {
} vi >& g , vi & btoa , vi & seen [ e ] = true ;
best = min ( best , { w [ t ] - vis ) { q . push_back ( match [ e ]) ;
mat [ t ][ t ] , co [ t ]}) ; if ( btoa [ j ] == -1) return }
co [ s ]. insert ( co [ s ]. end () , 1; }
all ( co [ t ]) ) ; vis [ j ] = 1; int di = btoa rep (i ,0 , n ) if (! lfound [ i
rep (i ,0 , n ) mat [ s ][ i ] += [ j ]; ]) cover . push_back ( i ) ;
mat [ t ][ i ]; for ( int e : g [ di ]) rep (i ,0 , m ) if ( seen [ i ])
rep (i ,0 , n ) mat [ i ][ s ] = if (! vis [ e ] && find (e , g , cover . push_back ( n + i ) ;
mat [ s ][ i ]; btoa , vis ) ) { assert ( sz ( cover ) == res ) ;
mat [0][ t ] = INT_MIN ; btoa [ e ] = di ; return cover ;
} return 1; }
return best ; }
} return 0; WeightedMatching.h
} Given a weighted bipartite graph,
GomoryHu.h int dfsMatching ( vector < vi matches every node on the left with a
Given a list of edges representing an >& g , vi & btoa ) { node on the right such that no nodes
undirected flow graph, returns edges vi vis ; are in two matchings and the sum of
of the Gomory-Hu tree. The max rep (i ,0 , sz ( g ) ) { the edge weights is minimal. Takes
flow between any pair of vertices is vis . assign ( sz ( btoa ) , 0) ; cost[N][M], where cost[i][j] = cost for
given by minimum edge weight along for ( int j : g [ i ]) L[i] to be matched with R[j] and re-
the Gomory-Hu tree path. if ( find (j , g , btoa , vis ) turns (min cost, match), where L[i]
) { is matched with R[match[i]]. Negate
btoa [ j ] = i ; costs for max cost.
typedef array < ll , 3 > Edge break ;
; }
vector < Edge > gomoryHu ( int }
N , vector < Edge > ed ) { return sz ( btoa ) - ( int ) pair < int , vi > hungarian (
vector < Edge > tree ; count ( all ( btoa ) , -1) ; const vector < vi > & a ) {
vi par ( N ) ; } if ( a . empty () ) return {0 ,
rep (i ,1 , N ) { {}};
PushRelabel D ( N ) ; // MinimumVertexCover.h int n = sz ( a ) + 1 , m = sz
Dinic a lso works Finds a minimum vertex cover in a ( a [0]) + 1;
for ( Edge t : ed ) D . bipartite graph. The size is the same vi u ( n ) , v ( m ) , p ( m ) , ans (
addEdge ( t [0] , t [1] , t as the size of a maximum matching, n - 1) ;
[2] , t [2]) ; and the complement is a maximum rep (i ,1 , n ) {
tree . push_back ({ i , par [ i independent set. p [0] = i ;
] , D . calc (i , par [ i ]) }) int j0 = 0; // add
; dummy worker 0
rep (j , i +1 , N ) vi cover ( vector < vi >& g , vi dist (m , INT_MAX ) , pre (
if ( par [ j ] == par [ i ] && D int n , int m ) { m , -1) ;
. leftOfMinCut ( j ) ) par [ vi match (m , -1) ; vector < bool > done ( m + 1) ;
j] = i; int res = dfsMatching (g , do { // d i jks t ra
} match ) ; done [ j0 ] = true ;
return tree ; vector < bool > lfound (n , int i0 = p [ j0 ] , j1 , delta
} true ) , seen ( m ) ; = INT_MAX ;
for ( int it : match ) if ( rep (j ,1 , m ) if (! done [ j ])
DFSMatching.h it != -1) lfound [ it ] = {
Simple bipartite matching algorithm. false ; auto cur = a [ i0 - 1][ j -
1] - u [ i0 ] - v [ j ]; ncomps ++; return top ;
if ( cur < dist [ j ]) dist [ j } }
] = cur , pre [ j ] = j0 ; return val [ j ] = low ; template < class F >
if ( dist [ j ] < delta ) } void bicomps ( F f ) {
delta = dist [ j ] , j1 = template < class G , class F num . assign ( sz ( ed ) , 0) ;
j; > void scc ( G & g , F f ) rep (i ,0 , sz ( ed ) ) if (! num [
} { i ]) dfs (i , -1 , f ) ;
rep (j ,0 , m ) { int n = sz ( g ) ; }
if ( done [ j ]) u [ p [ j ]] += val . assign (n , 0) ; comp .
delta , v [ j ] -= delta ; assign (n , -1) ; EulerWalk.h
else dist [ j ] -= delta ; Time = ncomps = 0; Eulerian undirected/directed path/-
} rep (i ,0 , n ) if ( comp [ i ] < cycle algorithm. Input should be a
j0 = j1 ; 0) dfs (i , g , f ) ; vector of (dest, global edge index),
} while ( p [ j0 ]) ; } where for undirected graphs, for-
while ( j0 ) { // update a ward/backward edges have the same
lternating path BiconnectedComponents.h index. Returns a list of nodes in the
int j1 = pre [ j0 ]; Finds all biconnected components Eulerian path/cycle with src at both
p [ j0 ] = p [ j1 ] , j0 = j1 ; in an undirected graph, and runs a start and end, or empty list if no cy-
} callback for the edges in each. In cle/path exists. To get edge indices
} a biconnected component there are back, add .second to s and ret.
rep (j ,1 , m ) if ( p [ j ]) ans [ at least two distinct paths between
p [ j ] - 1] = j - 1; any two nodes. Note that a node
return { - v [0] , ans }; // can be in several components. An vi eulerWalk ( vector <
min cost edge which is not in a component is vector < pii > >& gr , int
a bridge, i.e., not part of any cycle. nedges , int src =0) {
SCC.h int n = sz ( gr ) ;
Finds strongly connected compo- vi D ( n ) , its ( n ) , eu (
nents in a directed graph. If vertices vi num , st ; nedges ) , ret , s = { src
u, v belong to the same component, vector < vector < pii > > ed ; };
we can reach u from v and vice versa. int Time ; D [ src ]++; // to allow
Usage: scc(graph, [](vi v) ... ) visits template < class F > Euler paths , not jus
all components in reverse topological int dfs ( int at , int par , t cyc les
order. comp[i] holds the compo- F& f) { while (! s . empty () ) {
nent index of a node (a component int me = num [ at ] = ++ Time int x = s . back () , y , e , &
only has edges to components with , e , y , top = me ; it = its [ x ] , end = sz (
lower index). ncomps will contain for ( auto pa : ed [ at ]) if gr [ x ]) ;
the number of components. ( pa . second != par ) { if ( it == end ) { ret .
tie (y , e ) = pa ; push_back ( x ) ; s .
if ( num [ y ]) { pop_back () ; continue ;
vi val , comp , z , cont ; top = min ( top , num [ y ]) ; }
int Time , ncomps ; if ( num [ y ] < me ) tie (y , e ) = gr [ x ][ it ++];
template < class G , class F st . push_back ( e ) ; if (! eu [ e ]) {
> int dfs ( int j , G & g , } else { D [ x ] - - , D [ y ]++;
F& f) { int si = sz ( st ) ; eu [ e ] = 1; s . push_back ( y )
int low = val [ j ] = ++ Time int up = dfs (y , e , f ) ; ;
, x ; z . push_back ( j ) ; top = min ( top , up ) ; }}
for ( auto e : g [ j ]) if ( if ( up == me ) { for ( int x : D ) if ( x < 0
comp [ e ] < 0) st . push_back ( e ) ; || sz ( ret ) != nedges
low = min ( low , val [ e ] ?: f ( vi ( st . begin () + si , st . +1) return {};
dfs (e ,g , f ) ) ; end () ) ) ; return { ret . rbegin () , ret
if ( low == val [ j ]) { st . resize ( si ) ; . rend () };
do { } }
x = z . back () ; z . pop_back else if ( up < me ) st .
() ; push_back ( e ) ; EdgeColoring.h
comp [ x ] = ncomps ; else { / e is a bridge Given a simple, undirected graph
cont . push_back ( x ) ; / } with max degree D, computes a
} while ( x != j ) ; } (D + 1)-coloring of the edges such
f ( cont ) ; cont . clear () ; } that no neighboring edges share a
color. (D-coloring is NP-hard, but } li . push_back ( lca . lca (a , b
can be done for bipartite graphs by ));
repeated matchings of max-degree MaximalCliques.h }
nodes.) Time: O (NM) Runs a callback for all maximal sort ( all ( li ) , cmp ) ;
cliques in a graph (given as a sym- li . erase ( unique ( all ( li ) ) ,
vi edgeColoring ( int N , metric bitset matrix; self-edges not li . end () ) ;
vector < pii > eds ) { allowed). Callback is given a bitset rep (i ,0 , sz ( li ) ) rev [ li [ i
vi cc ( N + 1) , ret ( sz ( eds ) representing the maximal clique.
]] = i ;
) , fan ( N ) , free ( N ) ,
vpi ret = { pii (0 , li [0])
loc ;
};
for ( pii e : eds ) ++ cc [ e . typedef bitset <128 > B ;
rep (i ,0 , sz ( li ) -1) {
first ] , ++ cc [ e . second template < class F > int a = li [ i ] , b = li [ i
]; void cliques ( vector <B >& +1];
int u , v , ncols = * eds , F f , B P = B () ret . emplace_back ( rev [ lca .
max_element ( all ( cc ) ) + , B X ={} , B R ={}) { lca (a , b ) ] , b ) ;
1; if (! P . any () ) { if (! X . }
vector < vi > adj (N , vi ( any () ) f ( R ) ; return ; } return ret ;
ncols , -1) ) ; auto q = ( P | X ) . }
for ( pii e : eds ) { _Find_first () ;
tie (u , v ) = e ; auto cands = P & eds [ q lineDistance.h
fan [0] = v ; ]; Returns the signed distance between
loc . assign ( ncols , 0) ; rep (i ,0 , sz ( eds ) ) if ( point p and the line containing points
int at = u , end = u , d , c cands [ i ]) { a and b. Positive value on left side
= free [ u ] , ind = 0 , i R [ i ] = 1; and negative on right as seen from a
= 0; cliques ( eds , f , P & eds [ i towards b. a==b gives nan. P is sup-
while ( d = free [ v ] , ! loc [ ] , X & eds [ i ] , R ) ; posed to be Point¡T¿ or Point3D¡T¿
d ] && ( v = adj [ u ][ d ]) R [ i ] = P [ i ] = 0; X [ i ] = where T is e.g. double or long long.
!= -1) 1; It uses products in intermediate steps
loc [ d ] = ++ ind , cc [ ind ] = } so watch out for overflow if using int
d , fan [ ind ] = v ; } or long long. Using Point3D will al-
cc [ loc [ d ]] = c ; ways give a non-negative distance.
for ( int cd = d ; at != CompressTree.h For Point3D, call .dist on the result
-1; cd ^= c ^ d , at = Given a rooted tree and a subset S of the cross product.
adj [ at ][ cd ]) of nodes, compute the minimal sub-
swap ( adj [ at ][ cd ] , adj [ end tree that contains all the nodes by
= at ][ cd ^ c ^ d ]) ; adding all (at most —S— 1) pair- template < class P >
while ( adj [ fan [ i ]][ d ] != wise LCA’s and compressing edges. double lineDist ( const P &
-1) { Returns a list of (par, orig index) a , const P & b , const P
int left = fan [ i ] , right representing a tree rooted at 0. The & p) {
= fan [++ i ] , e = cc [ i ]; root points to itself. return ( double ) (b - a ) .
adj [ u ][ e ] = left ; cross (p - a ) /( b - a ) . dist
adj [ left ][ e ] = u ; () ;
adj [ right ][ e ] = -1; typedef vector < pair < int , }
free [ right ] = e ; int > > vpi ;
} vpi compressTree ( LCA & lca SegmentDistance.h
adj [ u ][ d ] = fan [ i ]; , const vi & subset ) { Returns the shortest distance be-
adj [ fan [ i ]][ d ] = u ; static vi rev ; rev . resize tween point p and the line segment
for ( int y : { fan [0] , u , ( sz ( lca . time ) ) ; from point s to e.
end }) vi li = subset , & T = lca .
for ( int & z = free [ y ] = time ;
0; adj [ y ][ z ] != -1; z auto cmp = [&]( int a , int typedef Point < double > P ;
++) ; b ) { return T [ a ] < T [ double segDist ( P & s , P & e
} b ]; }; , P& p) {
rep (i ,0 , sz ( eds ) ) sort ( all ( li ) , cmp ) ; if ( s == e ) return (p - s ) .
for ( tie (u , v ) = eds [ i ]; int m = sz ( li ) -1; dist () ;
adj [ u ][ ret [ i ]] != v ;) rep (i ,0 , m ) { auto d = (e - s ) . dist2 () , t
++ ret [ i ]; int a = li [ i ] , b = li [ i = min (d , max (.0 ,( p - s ) .
return ret ; +1]; dot (e - s ) ) ) ;
return (( p - s ) *d -( e - s ) * t ) . and the intersection point does not
dist () / d ; have integer coordinates. Products template < class P > bool
} of three coordinates are used in in- onSegment ( P s , P e , P
termediate steps so watch out for p) {
SegmentIntersection.h overflow if using int or ll. return p . cross (s , e ) == 0
If a unique intersection point be- && ( s - p ) . dot ( e - p )
tween the line segments going from <= 0;
s1 to e1 and from s2 to e2 exists then template < class P > }
it is returned. If no intersection point pair < int , P > lineInter ( P
linearTransformation.h
exists an empty vector is returned. s1 , P e1 , P s2 , P e2 )
Apply the linear transformation
If infinitely many exist a vector with {
(translation, rotation and scaling)
2 elements is returned, containing auto d = ( e1 - s1 ) . cross (
which takes line p0-p1 to line q0-q1
the endpoints of the common line e2 - s2 ) ;
to point r.
segment. The wrong position will if ( d == 0) // i f pa ra
be returned if P is Point¡ll¿ and the l l e l
intersection point does not have in- return { -( s1 . cross ( e1 , s2 typedef Point < double > P ;
teger coordinates. Products of three ) == 0) , P (0 , 0) }; P linearTransformation (
coordinates are used in intermediate auto p = s2 . cross ( e1 , e2 ) const P & p0 , const P &
steps so watch out for overflow if us- , q = s2 . cross ( e2 , s1 ) p1 ,
ing int or long long. ; const P & q0 , const P & q1 ,
return {1 , ( s1 * p + e1 * const P & r ) {
q ) / d }; P dp = p1 - p0 , dq = q1 - q0 ,
template < class P > vector < } num ( dp . cross ( dq ) , dp .
P > segInter ( P a , P b ,
dot ( dq ) ) ;
P c, P d) { sideOf.h
return q0 + P (( r - p0 ) .
auto oa = c . cross (d , a ) , Returns where p is as seen from s
cross ( num ) , (r - p0 ) . dot
ob = c . cross (d , b ) , towards e. 1/0/-1 left/on line/right.
( num ) ) / dp . dist2 () ;
oc = a . cross (b , c ) , od = If the optional argument eps is given
}
a . cross (b , d ) ; 0 is returned if p is within distance
// Checks i f eps from the line. P is supposed to CircleIntersection.h
intersection is s ing be Point¡T¿ where T is e.g. double Computes the pair of points at which
le n o n endpoint or long long. It uses products in two circles intersect. Returns false
point . intermediate steps so watch out for in case of no intersection.
if ( sgn ( oa ) * sgn ( ob ) < 0 overflow if using int or long long.
&& sgn ( oc ) * sgn ( od )
< 0) typedef Point < double > P ;
return {( a * ob - b * oa ) template < class P > bool circleInter ( P a , P b ,
/ ( ob - oa ) }; int sideOf ( P s , P e , P p ) double r1 , double r2 ,
set <P > s ; { return sgn ( s . cross ( pair <P , P >* out ) {
if ( onSegment (c , d , a ) ) s e, p)); } if ( a == b ) { assert ( r1
. insert ( a ) ; template < class P > != r2 ) ; return false ;
if ( onSegment (c , d , b ) ) s int sideOf ( const P & s , }
. insert ( b ) ; const P & e , const P & p P vec = b - a ;
if ( onSegment (a , b , c ) ) s , double eps ) { double d2 = vec . dist2 () ,
. insert ( c ) ; auto a = (e - s ) . cross (p - s ) sum = r1 + r2 , dif = r1 -
if ( onSegment (a , b , d ) ) s ; r2 ,
. insert ( d ) ; double l = (e - s ) . dist () * p = ( d2 + r1 * r1 - r2 * r2 )
return { all ( s ) }; eps ; /( d2 *2) , h2 = r1 * r1 -
} return ( a > l ) - ( a < -l ) p * p * d2 ;
; if ( sum * sum < d2 || dif *
lineIntersection.h } dif > d2 ) return false
If a unique intersection point of the ;
lines going through s1,e1 and s2,e2 OnSegment.h P mid = a + vec *p , per =
exists 1, point is returned. If no in- Returns true iff p lies on the vec . perp () * sqrt ( fmax
tersection point exists 0, (0,0) is re- line segment from s to e. Use (0 , h2 ) / d2 ) ;
turned and if infinitely many exists (segDist(s,e,p)¡=epsilon) instead * out = { mid + per , mid -
-1, (0,0) is returned. The wrong posi- when using Point¡double¿. per };
tion will be returned if P is Point¡ll¿ return true ;
} auto a = d . dot ( p ) / d . dist2 shuffle ( all ( ps ) , mt19937 (
() , b = ( p . dist2 () -r * r time (0) ) ) ;
CircleTangents.h ) / d . dist2 () ; P o = ps [0];
Finds the external tangents of two auto det = a * a - b ; double r = 0 , EPS = 1 + 1
circles, or internal if r2 is negated. if ( det <= 0) return arg ( e -8;
Can return 0, 1, or 2 tangents – 0 p , q ) * r2 ; rep (i ,0 , sz ( ps ) ) if (( o -
if one circle contains the other (or auto s = max (0. , -a - sqrt ( ps [ i ]) . dist () > r *
overlaps it, in the internal case, or det ) ) , t = min (1. , -a + EPS ) {
if the circles are the same); 1 if the sqrt ( det ) ) ; o = ps [ i ] , r = 0;
circles are tangent to each other (in if ( t < 0 || 1 <= s ) rep (j ,0 , i ) if (( o - ps [ j
which case .first = .second and the return arg (p , q ) * r2 ; ]) . dist () > r * EPS ) {
tangent line is perpendicular to the P u = p + d * s, v = p + o = ( ps [ i ] + ps [ j ]) / 2;
line between the centers). .first and d * t; r = ( o - ps [ i ]) . dist () ;
.second give the tangency points at return arg (p , u ) * r2 + u . rep (k ,0 , j ) if (( o - ps [ k
circle 1 and 2 respectively. To find cross ( v ) /2 + arg (v , q ) ]) . dist () > r * EPS ) {
the tangents of a circle with a point * r2 ; o = ccCenter ( ps [ i ] , ps [ j
set r2 to 0. }; ] , ps [ k ]) ;
auto sum = 0.0; r = ( o - ps [ i ]) . dist () ;
rep (i ,0 , sz ( ps ) ) }
template < class P > sum += tri ( ps [ i ] - c , ps }
vector < pair <P , P > > [( i + 1) % sz ( ps ) ] - c }
tangents ( P c1 , double ); return {o , r };
r1 , P c2 , double r2 ) { return sum ; }
P d = c2 - c1 ; }
double dr = r1 - r2 , d2 = InsidePolygon.h
d . dist2 () , h2 = d2 - circumcircle.h Returns true if p lies within the poly-
dr * dr ; The circumcirle of a triangle is the gon. If strict is true, it returns false
if ( d2 == 0 || h2 < 0) circle intersecting all three vertices. for points on the boundary. The
return {}; ccRadius returns the radius of the algorithm uses products in interme-
vector < pair <P , P > > out ; circle going through points A, B and diate steps so watch out for overflow.
for ( double sign : { -1 , C and ccCenter returns the center of Usage: vector¡P¿ v = P4,4, P1,2,
1}) { the same circle. P2,1; bool in = inPolygon(v, P3, 3,
P v = ( d * dr + d . perp () false);
* sqrt ( h2 ) * sign ) /
d2 ; typedef Point < double > P ;
out . push_back ({ c1 + v * double ccRadius ( const P & template < class P >
r1 , c2 + v * r2 }) ; A , const P & B , const P bool inPolygon ( vector <P >
} & C) { &p , P a , bool strict =
if ( h2 == 0) out . pop_back return (B - A ) . dist () *( C - B ) true ) {
() ; . dist () *( A - C ) . dist () / int cnt = 0 , n = sz ( p ) ;
return out ; abs (( B - A ) . cross (C - A ) ) /2; rep (i ,0 , n ) {
} } P q = p [( i + 1) % n ];
P ccCenter ( const P & A , if ( onSegment ( p [ i ] , q , a )
CirclePolygonIntersection.h const P & B , const P & C ) return ! strict ;
Returns the area of the intersection ) { // or : i f ( segDist ( p [ i
of a circle with a ccw polygon. P b = C -A , c = B - A ; ] , q , a ) <= eps )
return A + ( b * c . dist2 () -c return ! s t r i c t ;
* b . dist2 () ) . perp () / b . cnt ^= (( a .y < p [ i ]. y ) - ( a
typedef Point < double > P ; cross ( c ) /2; .y < q . y ) ) * a . cross ( p [ i
# define arg (p , q ) atan2 ( p } ] , q ) > 0;
. cross ( q ) , p . dot ( q ) ) }
double circlePoly ( P c , MinimumEnclosingCircle.h return cnt ;
double r , vector <P > ps Computes the minimum circle that }
) { encloses a set of points.
auto tri = [&]( P p , P q ) PolygonArea.h
{ Returns twice the signed area of
auto r2 = r * r / 2; pair <P , double > mec ( a polygon. Clockwise enumeration
P d = q - p; vector <P > ps ) { gives negative area. Watch out for
overflow if using int as T! } PointInsideHull.h
Determine whether a point t lies in-
ConvexHull.h side a convex hull (CCW order, with
template < class T > Returns a vector of the points of the no collinear points). Returns true if
T polygonArea2 ( vector < convex hull in counterclockwise or- point lies within the hull. If strict is
Point <T > >& v ) { der. Points on the edge of the hull true, points on the boundary aren’t
T a = v . back () . cross ( v between two other points are not included.
[0]) ; considered part of the hull.
rep (i ,0 , sz ( v ) -1) a += v [ i
]. cross ( v [ i +1]) ; typedef Point < ll > P ;
return a ; typedef Point < ll > P ; bool inHull ( const vector <
} vector <P > convexHull ( P >& l , P p , bool
vector <P > pts ) { strict = true ) {
PolygonCenter.h if ( sz ( pts ) <= 1) return int a = 1 , b = sz ( l ) - 1 ,
Returns the center of mass for a pts ; r = ! strict ;
polygon sort ( all ( pts ) ) ; if ( sz ( l ) < 3) return r
vector <P > h ( sz ( pts ) +1) ; && onSegment ( l [0] , l .
int s = 0 , t = 0; back () , p ) ;
typedef Point < double > P ;
for ( int it = 2; it - -; s if ( sideOf ( l [0] , l [ a ] , l [
P polygonCenter ( const
= --t , reverse ( all ( pts b ]) > 0) swap (a , b ) ;
vector <P >& v ) {
))) if ( sideOf ( l [0] , l [ a ] , p )
P res (0 , 0) ; double A =
for ( P p : pts ) { >= r || sideOf ( l [0] ,
0;
while ( t >= s + 2 && h [t l [ b ] , p ) <= -r )
for ( int i = 0 , j = sz ( v )
-2]. cross ( h [t -1] , p ) return false ;
- 1; i < sz ( v ) ; j = i
<= 0) t - -; while ( abs ( a - b ) > 1) {
++) {
h [ t ++] = p ; int c = ( a + b ) / 2;
res = res + ( v [ i ] + v [ j ])
} ( sideOf ( l [0] , l [ c ] , p ) >
* v [ j ]. cross ( v [ i ]) ;
return { h . begin () , h . 0 ? b : a) = c;
A += v [ j ]. cross ( v [ i ]) ;
begin () + t - ( t == 2 }
}
&& h [0] == h [1]) }; return sgn ( l [ a ]. cross ( l [ b
return res / A / 3;
} ], p)) < r;
}
}
PolygonCut.h HullDiameter.h
Returns a vector with the vertices of Returns the two points with max ClosestPair.h
a polygon with everything to the left distance on a convex hull (ccw, no : Finds the closest pair of points
of the line going from s to e cut away. duplicate/collinear points).

typedef Point < ll > P ;


typedef Point < double > P ; typedef Point < ll > P ; pair <P , P > closest ( vector
vector <P > polygonCut ( array <P , 2 > hullDiameter ( <P > v ) {
const vector <P >& poly , vector <P > S ) { assert ( sz ( v ) > 1) ;
P s, P e) { int n = sz ( S ) , j = n < 2 set <P > S ;
vector <P > res ; ? 0 : 1; sort ( all ( v ) , []( P a , P b )
rep (i ,0 , sz ( poly ) ) { pair < ll , array <P , 2 > > res { return a . y < b . y ;
P cur = poly [ i ] , prev = i ({0 , { S [0] , S [0]}}) ; }) ;
? poly [i -1] : poly . rep (i ,0 , j ) pair < ll , pair <P , P > > ret {
back () ; for (;; j = ( j + 1) % n ) LLONG_MAX , { P () , P ()
bool side = s . cross (e , { }};
cur ) < 0; res = max ( res , {( S [ i ] - S int j = 0;
if ( side != ( s . cross (e , [ j ]) . dist2 () , { S [ i ] , S for ( P p : v ) {
prev ) < 0) ) [ j ]}}) ; P d {1 + ( ll ) sqrt ( ret .
res . push_back ( lineInter (s if (( S [( j + 1) % n ] - S [ j first ) , 0};
, e , cur , prev ) . second ]) . cross ( S [ i + 1] - S [ while ( v [ j ]. y <= p . y - d .
); i ]) >= 0) x ) S . erase ( v [ j ++]) ;
if ( side ) break ; auto lo = S . lower_bound ( p
res . push_back ( cur ) ; } - d ) , hi = S .
} return res . second ; upper_bound ( p + d ) ;
return res ; } for (; lo != hi ; ++ lo )
ret = min ( ret , {(* lo - p ) KMP.h
. dist2 () , {* lo , p }}) ; : pi[x] computes the length of the array < vi , 2 > manacher (
S . insert ( p ) ; longest prefix of s that ends at x, const string & s ) {
} other than s[0...x] itself (abacaba -¿ int n = sz ( s ) ;
return ret . second ; 0010123). Can be used to find all array < vi ,2 > p = { vi ( n +1) ,
} occurrences of a string. vi ( n ) };
PolyhedronVolume.h rep (z ,0 ,2) for ( int i =0 , l
Magic formula for the volume of a =0 , r =0; i < n ; i ++) {
vi pi ( const string & s ) {
polyhedron. Faces should point out- int t = r - i +! z ;
vi p ( sz ( s ) ) ;
wards. if (i < r ) p [ z ][ i ] = min (t ,
rep (i ,1 , sz ( s ) ) {
p [ z ][ l + t ]) ;
int g = p [i -1];
int L = i - p [ z ][ i ] , R = i +
while ( g && s [ i ] != s [ g ])
template < class V , class L p [ z ][ i ] -! z ;
g = p [g -1];
> while (L >=1 && R +1 < n && s
p [ i ] = g + ( s [ i ] == s [ g ])
double signedPolyVolume ( [L -1] == s [ R +1])
;
const V & p , const L & p [ z ][ i ]++ , L - - , R ++;
}
trilist ) { if (R > r ) l =L , r = R ;
return p ;
double v = 0; }
}
for ( auto i : trilist ) v return p ;
vi match ( const string & s ,
+= p [ i . a ]. cross ( p [ i . b }
const string & pat ) {
]) . dot ( p [ i . c ]) ; vi p = pi ( pat + \0 MinRotation.h
return v / 6; + s ) , res ; Finds the lexicographically smallest
} rep (i , sz ( p ) - sz ( s ) , sz ( p ) ) rotation of a string
if ( p [ i ] == sz ( pat ) ) res .
sphericalDistance.h
push_back ( i - 2 * sz (
Returns the shortest distance on the int minRotation ( string s )
pat ) ) ;
sphere with radius radius between {
return res ;
the points with azimuthal angles int a =0 , N = sz ( s ) ; s += s ;
}
(longitude) f1 (1) and f2 (2) from rep (b ,0 , N ) rep (k ,0 , N ) {
x axis and zenith angles (latitude) Zfunc.h if ( a + k == b || s [ a + k ] <
t1 (1) and t2 (2) from z axis (0 = z[x] computes the length of the s [ b + k ]) { b += max (0 , k
north pole). All angles measured longest common prefix of s[i:] and -1) ; break ;}
in radians. The algorithm starts by s, except z[0] = 0. (abacaba -¿ if ( s [ a + k ] > s [ b + k ]) { a
converting the spherical coordinates 0010301) = b ; break ; }
to cartesian coordinates so if that is }
what you have you can use only the return a ;
two last rows. dx*radius is then the vi Z ( string S ) { }
difference between the two points in vi z ( sz ( S ) ) ;
the x direction and d*radius is the int l = -1 , r = -1; Titre
total distance between the points. rep (i ,1 , sz ( S ) ) { Description
z [ i ] = i >= r ? 0 : min ( r
- i , z [ i - l ]) ;
double sphericalDistance ( # include < bits / stdc ++. h >
while ( i + z [ i ] < sz ( S )
double f1 , double t1 , int main () {
&& S [ i + z [ i ]] == S [ z [
double f2 , double t2 , cout < <1 < < endl ;
i ]])
double radius ) { }
z [ i ]++;
double dx = sin ( t2 ) * cos (
if ( i + z [ i ] > r ) IntervalContainer.h
f2 ) - sin ( t1 ) * cos ( f1 ) ;
l = i , r = i + z [ i ]; Add and remove intervals from a set
double dy = sin ( t2 ) * sin (
} of disjoint intervals. Will merge the
f2 ) - sin ( t1 ) * sin ( f1 ) ;
return z ; added interval with any overlapping
double dz = cos ( t2 ) - cos
} intervals in the set when adding. In-
( t1 ) ;
double d = sqrt ( dx * dx + tervals are [inclusive, exclusive).
Manacher.h
dy * dy + dz * dz ) ; For each position in a string, com-
return radius *2* asin ( d /2) putes p[0][i] = half length of longest set < pii >:: iterator
; even palindrome around pos i, p[1][i] addInterval ( set < pii >&
} = longest odd (half rounded down). is , int L , int R ) {
if ( L == R ) return is . end failure (or if G is empty). long ull ;
() ; struct FastMod {
auto it = is . lower_bound ull b , m ;
({ L , R }) , before = it ; template < class T > FastMod ( ull b ) : b ( b ) , m
while ( it != is . end () && vi cover ( pair <T , T > G , ( -1 ULL / b ) {}
it - > first <= R ) { vector < pair <T , T > > I ) ull reduce ( ull a ) { // a
R = max (R , it - > second ) ; { % b + (0 or b )
before = it = is . erase ( it vi S ( sz ( I ) ) , R ; return a - ( ull ) ((
); iota ( all ( S ) , 0) ; __uint128_t ( m ) * a ) >>
} sort ( all ( S ) , [&]( int a , 64) * b ;
if ( it != is . begin () && int b ) { return I [ a ] < }
( - - it ) -> second >= L ) { I [ b ]; }) ; };
L = min (L , it - > first ) ; T cur = G . first ;
R = max (R , it - > second ) ; int at = 0; FastInput.
is . erase ( it ) ; while ( cur < G . second ) { Read an integer from stdin. Usage
} // ( A ) requires your program to pipe in in-
return is . insert ( before , pair <T , int > mx = put from file
{L , R }) ; make_pair ( cur , -1) ;
} while ( at < sz ( I ) && I [ S [
void removeInterval ( set < at ]]. first <= cur ) {
pii >& is , int L , int R mx = max ( mx , make_pair ( I [ inline char gc () { // l i
) { S [ at ]]. second , S [ at ]) ) k e getchar ()
if ( L == R ) return ; ; static char buf [1 << 16];
auto it = addInterval ( is , at ++; static size_t bc , be ;
L, R); } if ( bc >= be ) {
auto r2 = it - > second ; if ( mx . second == -1) buf [0] = 0 , bc = 0;
if ( it - > first == L ) is . return {}; be = fread ( buf , 1 , sizeof
erase ( it ) ; cur = mx . first ; ( buf ) , stdin ) ;
else ( int &) it - > second = L R . push_back ( mx . second ) ; }
; } return buf [ bc ++]; //
if ( R != r2 ) is . emplace (R return R ; returns 0 on EOF
, r2 ) ; } }
} int readInt () {
FastMod.
int a , c ;
Compute aconstant but not known
IntervalCover.h while (( a = gc () ) < 40) ;
at compile time. Returns a value
Compute indices of smallest set of if ( a == - ) return
congruent to a (mod b) in the range
intervals covering another interval. - readInt () ;
[0, 2b).
Intervals should be [inclusive, ex- while (( c = gc () ) >= 48)
clusive). To support [inclusive, in- a = a * 10 + c - 480;
clusive], change (A) to add —— return a - 48;
[Link](). Returns empty set on typedef unsigned long

You might also like