跳到正文

个人记录

Atcoder Template Library

block_in_mc约 75 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月28日
篇幅
约 75 分钟
获赞
1

版本

  1. v1当前

Appendix / FAQ

Environments

  • Do not use the macro beginning with ATCODER_.
  • Although we aimed to make it work in many environments, it requires some C++ extension. We assume the following.
    • __int128 / unsigned __int128(g++, clang++) or _mul128 / _umul128(Visual Studio) works.
    • __builtin_(ctz/ctzll/clz/clzll/popcount)(g++, clang++) or _BitScan(Forward/Reverse)(Visual Studio) works.
    • char / short / int / ll and their unsigned types (and signed char) are 8 / 16 / 32 / 64 bits.
    • 💻 Signed integers are two’s complement.

How to Install

g++ / clang++

The easiest way is to put atcoder folder in the same place as main.cpp and execute g++ main.cpp -std=c++14 -I ., as noted in the index. Here, . is the symbol that represents the current directory (you should type a space and a period after I).

If you don’t want to copy atcoder folder manually, do as follows.

  • Specify the command like g++ main.cpp -std=c++14 -I /path/to/ac-library (/path/to/ac-library stands for the directory where the downloaded ac-library is located).
  • Specify the place of atcoder folder by the environment variable CPLUS_INCLUDE_PATH as CPLUS_INCLUDE_PATH="/path/to/ac-library". (On Windows, type like C:\path\to\ac-library in the field of the variable CPLUS_INCLUDE_PATH on the Window of Environment Variables. Note that, you should use backslashes, not slashes.) Then, you can compile just by g++ main.cpp -std=c++14.

Visual Studio

Visual Studio 2019 / 2022 is supported. Update it if you are using old Visual Studio.

If Visual Studio is installed, there is a folder like the following.

  • C:\Program Files\Microsoft Visual Studio\2022\(Community, Professional or Enterprise)\VC\Tools\MSVC\(Some number, e.g. 14.35.32215)\include
  • C:\Program Files (x86)\Microsoft Visual Studio\2019\(Community, Professional or Enterprise)\VC\Tools\MSVC\(Some number, e.g. 14.27.29110)\include

Copy atcoder folder into it, i.e., put it so that the path will be as follows.

  • C:\Program Files\Microsoft Visual Studio\2022\(Community, Professional or Enterprise)\VC\Tools\MSVC\(Some number, e.g. 14.35.32215)\include\atcoder\dsu.hpp

How to Submit to Other Online Judge Systems

We prepared the script expander.py (python3.5 or later). The code combined.cpp, which can be compiled on other online judge systems, is generated by executing python3 expander.py main.cpp.

Although we tested it, we do not guarantee that it works correctly.

Preliminaries

💻Mark

This mark represents that the part, e.g., modint, may be difficult to use if you do not know much about C++. AC Library is designed to be still usable if you ignore the parts with this mark.

Template Function

For example, suffix_array(v) can take vector<int>, vector<ll>, et cetera as an argument. In this document, we unify these notations to suffix_array<T>(vector<T> v).

For example, to calculate the suffix array of the integral array vv stored in vector<int>, we can code as follows.

C++
vector<int> sa = suffix_array(v);
// vector<int> sa = suffix_array<int>(v); : wrong usage

Default Constructor

The structs like scc_graph can be declared not only like the former code, but also like the latter code without initialization.

C++
#include <atcoder/scc>;
using namespace atcoder;

int main() {
    int n;
    scanf("%d", &n);
    scc_graph g(n); // create the graph with n vertices
    return 0;
}
C++
#include <atcoder/scc>;
using namespace atcoder;

scc_graph g;

int main() {
    return 0;
}

If it is declared in the latter way, the behavior (of the default constructor) is as follows.

  • It takes O(1)O(1)-time.
  • The behavior is undefined if the member variables are accessed or the member functions are called.

You can also assign a value to the struct later.

C++
#include <atcoder/scc>;
using namespace atcoder;

scc_graph g;

int main() {
    g = scc_graph(10);
    return 0;
}

The Type of the Edges

In the graph libraries, the type mf_graph<Cap>::edge is used to store edges.

For example, the type of the edges of mf_graph<int> is mf_graph<int>::edge. If you are not familiar to ::, you can use the string mf_graph<int>::edge in the same manner as int or string, like the following example.

C++
vector<mf_graph<int>::edge> v;
mf_graph<int>::edge e;

Default Template Arguments

Sometimes the following notation is used, as in the document of convolution.

C++
vector<T> convolution<int m = 998244353>(vector<T> a, vector<T> b)

It means the default template argument. As the following example, you can call the function without explicitly specifying m.

C++
vector<long long> c = convolution(a, b);
vector<long long> c = convolution<924844033>(a, b);

In the first case, mm is automatically set to be 998244353998244353. In the second case, mm becomes the value that is explicitly specified, which is 924844033924844033 here.

💻 explicit specifier

Constructors of structs except modint are declared with the explicit specifier.

Precise requirements in Segtree / LazySegtree

In some situations, the cardinality of algebraic structures for Segtree / LazySegtree would be infinite. In precise meaning, it may break the constraints in the document.

For example, for the typical LazySegtree on S=intS = \mathrm{int} that processes the queries of range max and range addition, SS is not closed under addition due to the overflow. To resolve this problem, it is ensured to work correctly in the following situation.

Segtree

  • SS is an algebraic structure that satisfies the properties in the document.
  • e∈S′⊆Se \in S' \subseteq S
  • If the arguments and the results are in S′S', the types and operations work correctly.
  • For any moment, every contigurous subsequence al,al+1,⋯ ,ar−1a_l, a_{l+1}, \cdots, a_{r-1} satisfies al⋅al+1⋅…⋅ar−1∈S′a_l \cdot a_{l+1} \cdot \ldots \cdot a_{r-1}\in S'.

LazySegtree

  • (S,F)(S, F) is a pair of algebraic structures that satisfies the properties in the document.
  • e∈S′⊆S,id∈F′⊆Fe \in S' \subseteq S, \mathrm{id} \in F' \subseteq F
  • If the arguments and the results are in S′S' or F′F', the types and operations work correctly.
  • For any moment, every contigurous subsequence al,al+1,⋯ ,ar−1a_l, a_{l+1}, \cdots, a_{r-1} satisfies al⋅al+1⋅…⋅ar−1∈S′a_l \cdot a_{l+1} \cdot \ldots \cdot a_{r-1}\in S'.
  • Let us fix an element and denote the maps acted on it by f0,f1,...,fk−1∈Ff_0, f_1, ..., f_{k-1} \in F in this order. Then, for every contigurous subsequence fl,⋯ ,fr−1f_l, \cdots, f_{r-1}, fr−1∘fl+1∘⋯∘fl∈F′f_{r-1} \circ f_{l+1} \circ \dots \circ f_{l} \in F'.

Above LazySegtree can naturally be defined as follows, using infinite algebraic structures SS and FF.

  • S=Z∪{−∞}S = \mathbb{Z} \cup \{-\infty\}
  • The binary operation ⋅\cdot on SS is max\mathrm{max} and e=−∞e = -\infty.
  • FF is the set of the maps that adds a constant integer (id\mathrm{id} is the map that adds 00).

Under some sufficiently small constraints, it can be treated by this library by setting (S′,F′)(S', F') as follows.

  • S′=(Z∩(−231,231))∪{−∞}S' = (\mathbb{Z} \cap (-2^{31}, 2^{31})) \cup \{-\infty\}
  • S′S' is represented by int\mathrm{int}. The element x∈S′x\in S' is represented as xx in int\mathrm{int} if x≠−∞x \neq -\infty and −231-2^{31} if x=−∞x = -\infty.
  • F′F' is the set of the maps that adds a constant integer in [−231,231)[-2^{31}, 2^{31}) and represented naturally using the type int\mathrm{int}.

The Behavior of maxflow

Internally, for each edge ee, it stores the flow amount fef_e and the capacity cec_e. Let out(v)\mathrm{out}(v) and in(v)\mathrm{in}(v) be the set of edges starts and ends at vv, respectively. For each vertex vv, let g(v,f)=∑e∈in(v)fe−∑e∈out(v)feg(v, f) = \sum_{e \in \mathrm{in}(v)}{f_e} - \sum_{e \in \mathrm{out}(v)}{f_e}.

flow(s, t)

It changes the flow amount of each edge. Let fef_e and fe′f'_e be the flow amount of edge ee before and after calling it, respectively. Precisely, it changes the flow amount as follows.

  • 0≤fe′≤ce0 \leq f'_e \leq c_e
  • g(v,f)=g(v,f′)g(v, f) = g(v, f') holds for all vertices vv other than ss and tt.
  • If flow_limit is specified, g(t,f′)−g(t,f)≤flowlimitg(t, f') - g(t, f) \leq \mathrm{flow\\_limit}.
  • g(t,f′)−g(t,f)g(t, f') - g(t, f) is maximized under these conditions. It returns this g(t,f′)−g(t,f)g(t, f') - g(t, f).

min_cut(s)

The residual network is the graph whose edge set is given by gathering (u,v)(u, v) for each edge e=(u,v,fe,ce)e = (u, v, f_e, c_e) with fe<cef_e \lt c_e and (v,u)(v, u) for each edge ee with 0<fe0 \lt f_e. It returns the set of the vertices that is reachable from ss in the residual network.

change_edge(i, new_cap, new_flow)

It changes the flow amount and the capacity of the edge ii to new_flow and new_cap, respectively. It doesn’t change other values.

Convolution

It calculates (+,×)(+,\times) convolution. Given two arrays a0,a1,⋯ ,aN−1a_0, a_1, \cdots, a_{N - 1} and b0,b1,⋯ ,bM−1b_0, b_1, \cdots, b_{M - 1}, it calculates the array cc of length N+M−1N + M - 1, defined by

ci=∑j=0iajbi−jc_i = \sum_{j = 0}^i a_j b_{i - j}

convolution

C++
(1) vector<T> convolution<int m = 998244353>(vector<T> a, vector<T> b)
💻(2) vector<static_modint<m>> convolution<int m>(vector<static_modint<m>> a, vector<static_modint<m>> b)

It calculates the convolution in  mod m\bmod m. It returns an empty array if at least one of aa and bb are empty.

@{keyword.constraints}

  • 2≤m≤2×1092 \leq m \leq 2 \times 10^9
  • mm is prime.
  • There is an integer cc with 2c∣(m−1)2^c | (m - 1) and ∣a∣+∣b∣−1≤2c|a| + |b| - 1 \leq 2^c.
  • (1) T is int, uint, ll, or ull.

@{keyword.complexity}

  • O(nlog⁡n+log⁡mod)O(n\log{n} + \log{\mathrm{mod}}), where n=∣a∣+∣b∣n = |a| + |b|.

convolution_ll

C++
vector<ll> convolution_ll(vector<ll> a, vector<ll> b)

It calculates the convolution. It returns an empty array if at least one of aa and bb are empty.

@{keyword.constraints}

  • ∣a∣+∣b∣−1≤224|a| + |b| - 1 \leq 2^{24}
  • All the elements of the array are in ll after convolution

@{keyword.complexity}

  • O(nlog⁡n)O(n\log{n}), where n=∣a∣+∣b∣n = |a| + |b|.

DSU

Given an undirected graph, it processes the following queries in O(α(n))O(\alpha(n)) time (amortized).

  • Edge addition
  • Deciding whether given two vertices are in the same connected component

Each connected component internally has a representative vertex.

When two connected components are merged by edge addition, one of the two representatives of these connected components becomes the representative of the new connected component.

Constructor

C++
dsu d(int n)
  • It creates an undirected graph with nn vertices and 00 edges.

@{keyword.constraints}

  • 0≤n≤1080 \leq n \leq 10^8

@{keyword.complexity}

  • O(n)O(n)

merge

C++
int d.merge(int a, int b)

It adds an edge (a,b)(a, b).

If the vertices aa and bb were in the same connected component, it returns the representative of this connected component. Otherwise, it returns the representative of the new connected component.

@{keyword.constraints}

  • 0≤a<n0 \leq a < n
  • 0≤b<n0 \leq b < n

@{keyword.complexity}

  • O(α(n))O(\alpha(n)) amortized

same

C++
bool d.same(int a, int b)

It returns whether the vertices aa and bb are in the same connected component.

@{keyword.constraints}

  • 0≤a<n0 \leq a < n
  • 0≤b<n0 \leq b < n

@{keyword.complexity}

  • O(α(n))O(\alpha(n)) amortized

leader

C++
int d.leader(int a)

It returns the representative of the connected component that contains the vertex aa.

@{keyword.constraints}

  • 0≤a<n0 \leq a < n

@{keyword.complexity}

  • O(α(n))O(\alpha(n)) amortized

size

C++
int d.size(int a)

It returns the size of the connected component that contains the vertex aa.

@{keyword.constraints}

  • 0≤a<n0 \leq a < n

@{keyword.complexity}

  • O(α(n))O(\alpha(n)) amortized

groups

C++
vector<vector<int>> d.groups()

It divides the graph into connected components and returns the list of them.

More precisely, it returns the list of the “list of the vertices in a connected component”. Both of the orders of the connected components and the vertices are undefined.

@{keyword.complexity}

  • O(n)O(n)

Fenwick Tree

Given an array of length NN, it processes the following queries in O(log⁡N)O(\log N) time.

  • Updating an element
  • Calculating the sum of the elements of an interval

Constructor

C++
fenwick_tree<T> fw(int n)
  • It creates an array a0,a1,⋯ ,an−1a_0, a_1, \cdots, a_{n-1} of length nn. All the elements are initialized to 00.

@{keyword.constraints}

  • T is int, uint, ll, ull, or modint
  • 0≤n≤1080 \leq n \leq 10^8

@{keyword.complexity}

  • O(n)O(n)

add

C++
void fw.add(int p, T x)

It processes a[p] += x.

@{keyword.constraints}

  • 0≤p<n0 \leq p < n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

sum

C++
T fw.sum(int l, int r)

It returns a[l] + a[l + 1] + ... + a[r - 1]. If T is integer type(int, uint, ll, or ull), it returns the answer in  mod 2bit\bmod 2^{\mathrm{bit}}, if overflowed.

@{keyword.constraints}

  • 0≤l≤r≤n0 \leq l \leq r \leq n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

Lazy Segtree

It is the data structure for the pair of a monoid (S,⋅:S×S→S,e∈S)(S, \cdot: S \times S \to S, e \in S) and a set FF of S→SS \to S mappings that satisfies the following properties.

  • FF contains the identity map id\mathrm{id}, where the identity map is the map that satisfies id(x)=x\mathrm{id}(x) = x for all x∈Sx \in S.
  • FF is closed under composition, i.e., f∘g∈Ff \circ g \in F holds for all f,g∈Ff, g \in F.
  • f(x⋅y)=f(x)⋅f(y)f(x \cdot y) = f(x) \cdot f(y) holds for all f∈Ff \in F and x,y∈Sx, y \in S.

Given an array SS of length NN, it processes the following queries in O(log⁡N)O(\log N) time (see Appendix for further details).

  • Acting the map f∈Ff\in F (cf. x=f(x)x = f(x)) on all the elements of an interval
  • Calculating the product of the elements of an interval

For simplicity, in this document, we assume that the oracles op, e, mapping, composition, and id work in constant time. If these oracles work in O(T)O(T) time, each time complexity appear in this document is multipled by O(T)O(T).

Constructor

C++
(1) lazy_segtree<S, op, e, F, mapping, composition, id> seg(int n);
(2) lazy_segtree<S, op, e, F, mapping, composition, id> seg(vector<S> v);

The following should be defined.

  • The type S of the monoid
  • The binary operation S op(S a, S b)
  • The function S e() that returns ee
  • The type F of the map
  • The function S mapping(F f, S x) that returns f(x)f(x)
  • The function F composition(F f, F g) that returns f∘gf \circ g
  • The function F id() that returns id\mathrm{id}

See examples and here for further details.

  • (1): It creates an array a of length n. All the elements are initialized to e().
  • (2): It creates an array a of length n = v.size(), initialized to v.

@{keyword.constraints}

  • 0≤n≤1080 \leq n \leq 10^8

@{keyword.complexity}

  • O(n)O(n)

set

C++
void seg.set(int p, S x)

a[p] = x

@{keyword.constraints}

  • 0≤p<n0 \leq p < n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

get

C++
S seg.get(int p)

It returns a[p].

@{keyword.constraints}

  • 0≤p<n0 \leq p < n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

prod

C++
S seg.prod(int l, int r)

It returns op(a[l], ..., a[r - 1]), assuming the properties of the monoid. It returns e() if l=rl = r.

@{keyword.constraints}

  • 0≤l≤r≤n0 \leq l \leq r \leq n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

all_prod

C++
S seg.all_prod()

It returns op(a[0], ..., a[n - 1]), assuming the properties of the monoid. It returns e() if n=0n = 0.

@{keyword.complexity}

  • O(1)O(1)

apply

C++
(1) void seg.apply(int p, F f)
(2) void seg.apply(int l, int r, F f)
  • (1) It applies a[p] = f(a[p]).
  • (2) It applies a[i] = f(a[i]) for all i = l..r-1.

@{keyword.constraints}

  • (1) 0≤p<n0 \leq p < n
  • (2) 0≤l≤r≤n0 \leq l \leq r \leq n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

max_right

C++
(1) int seg.max_right<g>(int l)
(2 ) int seg.max_right<G>(int l, G g)
  • (1): It applies a binary search on the segment tree. The function bool g(S x) should be defined.
  • (2): The function object that takes S as the argument and returns bool should be defined.

It returns an index r that satisfies both of the followings.

  • r = l or g(op(a[l], a[l + 1], ..., a[r - 1])) = true
  • r = n or g(op(a[l], a[l + 1], ..., a[r])) = false

If g is monotone, this is the maximum r that satisfies g(op(a[l], a[l + 1], ..., a[r - 1])) = true.

@{keyword.constraints}

  • if g is called with the same argument, it returns the same value, i.e., g has no side effect.
  • g(e()) = true
  • 0≤l≤n0 \leq l \leq n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

min_left

C++
(1) int seg.min_left<g>(int r)
(2 ) int seg.min_left<G>(int r, G g)
  • (1): It applies a binary search on the segment tree. The function bool g(S x) should be defined.
  • (2): The function object that takes S as the argument and returns bool should be defined.

It returns an index l that satisfies both of the following.

  • l = r or g(op(a[l], a[l + 1], ..., a[r - 1])) = true
  • l = 0 or g(op(a[l - 1], a[l], ..., a[r - 1])) = false

If g is monotone, this is the minimum l that satisfies g(op(a[l], a[l + 1], ..., a[r - 1])) = true.

@{keyword.constraints}

  • if g is called with the same argument, it returns the same value, i.e., g has no side effect.
  • g(e()) = true
  • 0≤r≤n0 \leq r \leq n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

Math

It contains number-theoretic algorithms.

pow_mod

C++
ll pow_mod(ll x, ll n, int m)

It returns xn mod mx^n \bmod m.

@{keyword.constraints}

  • 0≤n0 \le n
  • 1≤m1 \le m

@{keyword.complexity}

  • O(log⁡n)O(\log n)

inv_mod

C++
ll inv_mod(ll x, ll m)

It returns an integer yy such that 0≤y<m0 \le y < m and xy≡1(modm)xy \equiv 1 \pmod m.

@{keyword.constraints}

  • gcd⁡(x,m)=1\gcd(x, m) = 1
  • 1≤m1 \leq m

@{keyword.complexity}

  • O(log⁡m)O(\log m)

crt

C++
pair<ll, ll> crt(vector<ll> r, vector<ll> m)

Given two arrays r,mr,m with length nn, it solves the modular equation system

x≡r[i](modm[i]),∀i∈{0,1,⋯ ,n−1}.x \equiv r[i] \pmod{m[i]}, \forall i \in \lbrace 0,1,\cdots, n - 1 \rbrace.

If there is no solution, it returns (0,0)(0, 0). Otherwise, all the solutions can be written as the form x≡y(modz)x \equiv y \pmod z, using integers y,zy, z (0≤y<z=lcm(m[i]))(0 \leq y < z = \mathrm{lcm}(m[i])). It returns this (y,z)(y, z) as a pair. If n=0n=0, it returns (0,1)(0, 1).

@{keyword.constraints}

  • ∣r∣=∣m∣|r| = |m|
  • 1≤m[i]1 \le m[i]
  • lcm(m[i])\mathrm{lcm}(m[i]) is in ll.

@{keyword.complexity}

  • O(nlog⁡lcm(m[i]))O(n \log{\mathrm{lcm}(m[i])})

floor_sum

C++
ll floor_sum(ll n, ll m, ll a, ll b)

It returns

∑i=0n−1⌊a×i+bm⌋\sum_{i = 0}^{n - 1} \left\lfloor \frac{a \times i + b}{m} \right\rfloor

It returns the answer in  mod 264\bmod 2^{\mathrm{64}}, if overflowed.

@{keyword.constraints}

  • 0≤n<2320 \leq n \lt 2^{32}
  • 1≤m<2321 \leq m \lt 2^{32}

@{keyword.complexity}

  • O(log⁡m)O(\log m)

MaxFlow

It solves maximum flow problem.

Constructor

C++
mf_graph<Cap> graph(int n)

It creates a graph of n vertices and 00 edges. Cap is the type of the capacity.

@{keyword.constraints}

  • 0≤n≤1080 \leq n \leq 10^8
  • Cap is int or ll

@{keyword.complexity}

  • O(n)O(n)

add_edge

C++
int graph.add_edge(int from, int to, Cap cap);

It adds an edge oriented from the vertex from to the vertex to with the capacity cap and the flow amount 00. It returns an integer kk such that this is the kk-th edge that is added.

@{keyword.constraints}

  • 0≤from,to<n0 \leq \mathrm{from}, \mathrm{to} \lt n
  • 0≤cap0 \leq \mathrm{cap}

@{keyword.complexity}

  • O(1)O(1) amortized

flow

C++
(1) Cap graph.flow(int s, int t);
(2) Cap graph.flow(int s, int t, Cap flow_limit);
  • (1) It augments the flow from ss to tt as much as possible. It returns the amount of the flow augmented.
  • (2) It augments the flow from ss to tt as much as possible, until reaching the amount of flow_limit. It returns the amount of the flow augmented.
  • You may call it multiple times. See Appendix for further details.

@{keyword.constraints}

  • s≠ts \neq t
  • 0≤s,t<n0 \leq s, t \lt n
  • The answer should be in Cap.

@{keyword.complexity}

  • O((n+m)m)O((n + m) \sqrt{m}) (if all the capacities are 11),
  • O(n2m)O(n^2 m) (general), or
  • O(F(n+m))O(F(n + m)), where FF is the returned value

where mm is the number of added edges.

min_cut

C++
vector<bool> graph.min_cut(int s)

It returns a vector of length nn, such that the ii-th element is true if and only if there is a directed path from ss to ii in the residual network. The returned vector corresponds to a s−ts-t minimum cut after calling flow(s, t) exactly once without flow_limit. See Appendix for further details.

@{keyword.complexity}

  • O(n+m)O(n + m), where mm is the number of added edges.

get_edge / edges

C++
struct mf_graph<Cap>::edge {
    int from, to;
    Cap cap, flow;
};

(1) mf_graph<Cap>::edge graph.get_edge(int i);
(2) vector<mf_graph<Cap>::edge> graph.edges();
  • It returns the current internal state of the edges.
  • The edges are ordered in the same order as added by add_edge.

@{keyword.constraints}

  • (1): 0≤i<m0 \leq i \lt m

@{keyword.complexity}

  • (1): O(1)O(1)
  • (2): O(m)O(m), where mm is the number of added edges.

change_edge

C++
void graph.change_edge(int i, Cap new_cap, Cap new_flow);

It changes the capacity and the flow amount of the ii-th edge to new_cap and new_flow, respectively. It doesn’t change the capacity or the flow amount of other edges. See Appendix for further details.

@{keyword.constraints}

  • 0≤newflow≤newcap0 \leq \mathrm{newflow} \leq \mathrm{newcap}

@{keyword.complexity}

  • O(1)O(1)

MinCostFlow

It solves Minimum-cost flow problem.

Constructor

C++
mcf_graph<Cap, Cost> graph(int n);

It creates a directed graph with nn vertices and 00 edges. Cap and Cost are the type of the capacity and the cost, respectively.

@{keyword.constraints}

  • 0≤n≤1080 \leq n \leq 10^8
  • Cap and Cost are int or ll.

@{keyword.complexity}

  • O(n)O(n)

add_edge

C++
int graph.add_edge(int from, int to, Cap cap, Cost cost);

It adds an edge oriented from from to to with capacity cap and cost cost. It returns an integer kk such that this is the kk-th edge that is added.

@{keyword.constraints}

  • 0≤from,to<n0 \leq \mathrm{from}, \mathrm{to} \lt n
  • 0≤cap,cost0 \leq \mathrm{cap}, \mathrm{cost}

@{keyword.complexity}

  • O(1)O(1) amortized

min_cost_max_flow

C++
(1) pair<Cap, Cost> graph.flow(int s, int t);
(2) pair<Cap, Cost> graph.flow(int s, int t, Cap flow_limit);
  • It augments the flow from ss to tt as much as possible. It returns the amount of the flow and the cost.
  • (1) It augments the s−ts-t flow as much as possible.
  • (2) It augments the s−ts-t flow as much as possible, until reaching the amount of flow_limit.

@{keyword.constraints}

  • same as min_cost_slope.

@{keyword.complexity}

  • same as min_cost_slope.

min_cost_slope

C++
vector<pair<Cap, Cost>> graph.slope(int s, int t);
vector<pair<Cap, Cost>> graph.slope(int s, int t, Cap flow_limit);

Let gg be a function such that g(x)g(x) is the cost of the minimum cost s−ts-t flow when the amount of the flow is exactly xx. gg is known to be piecewise linear. It returns gg as the list of the changepoints, that satisfies the followings.

  • The first element of the list is (0,0)(0, 0).
  • Both of .first and .second are strictly increasing.
  • No three changepoints are on the same line.
  • (1) The last element of the list is (x,g(x))(x, g(x)), where xx is the maximum amount of the s−ts-t flow.
  • (2) The last element of the list is (y,g(y))(y, g(y)), where y=min⁡(x,flowlimit)y = \min(x, \mathrm{flow\\_limit}).

@{keyword.constraints}

Let xx be the maximum cost among all edges.

  • s≠ts \neq t
  • 0≤s,t<n0 \leq s, t \lt n
  • You can’t call min_cost_slope or min_cost_max_flow multiple times.
  • The total amount of the flow is in Cap.
  • The total cost of the flow is in Cost.
  • (Cost : int): 0≤nx≤2×109+10000 \leq nx \leq 2 \times 10^9 + 1000
  • (Cost : ll): 0≤nx≤8×1018+10000 \leq nx \leq 8 \times 10^{18} + 1000

@{keyword.complexity}

  • O(F(n+m)log⁡(n+m))O(F (n + m) \log (n + m)), where FF is the amount of the flow and mm is the number of added edges.

edges

C++
struct edge<Cap, Cost> {
    int from, to;
    Cap cap, flow;
    Cost cost;
};

(1) mcf_graph<Cap, Cost>::edge graph.get_edge(int i);
(2) vector<mcf_graph<Cap, Cost>::edge> graph.edges();
  • It returns the current internal state of the edges.
  • The edges are ordered in the same order as added by add_edge.

@{keyword.constraints}

  • (1): 0≤i<m0 \leq i \lt m

@{keyword.complexity}

  • (1): O(1)O(1)
  • (2): O(m)O(m), where mm is the number of added edges.

Modint

It is the struct that treats the modular arithmetic. All the remaining parts of AC Library works without modint, so you don’t necessarily read this to use the remaining parts.

For most of the problems, it is sufficient to use modint998244353, modint1000000007, or modint, which can be used as follows.

C++
#include <atcoder/modint>
#include <iostream>

using namespace std;
using namespace atcoder;

using mint = modint998244353;
// or: typedef modint998244353 mint;

int main() {
    // print sum of array (mod 998244353)
    int n;
    cin >> n;
    mint sum = 0;
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        sum += x;
    }
    cout << sum.val() << endl;
}

If the mod is not fixed, you can use modint as follows.

C++
#include <atcoder/modint>
#include <iostream>

using namespace std;
using namespace atcoder;

using mint = modint;
// or: typedef modint mint;

int main() {
    // print sum of array (input mod)
    int n, mod;
    cin >> n >> mod;
    mint::set_mod(mod);
    mint sum = 0;
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        sum += x;
    }
    cout << sum.val() << endl;
}

All the functions except set_mod work for all three of them.

Constructor

C++
(1) modint x()
(2) modint x<T>(T y)
  • (1) It is the default constructor of modint. 00 will be stored.
  • (2) It is the constructor for the integer type T(int, char, ull, bool, ...). y is stored in modint after taking mod.

set_mod

C++
void modint::set_mod(int m)

It sets the mod. It must be called first.

@{keyword.constraints}

  • 1≤m≤2×109+10001 \leq m \leq 2 \times 10^9 + 1000

@{keyword.complexity}

  • O(1)O(1)

mod

C++
int modint::mod()

It returns the mod.

val

C++
int x.val();

It returns the value that is stored in x.

Operations

The following operations work.

C++
-modint;

modint++;
modint--;
++modint;
--modint;

modint + modint;
modint - modint;
modint * modint;
modint / modint;

modint += modint;
modint -= modint;
modint *= modint;
modint /= modint;

modint == modint;
modint != modint;

The following also works, because it is interpreted as modint(1) + x.

C++
modint x = 10;
1 + x;

The following also works, because it is interpreted as y * modint(z).

C++
modint::set_mod(11);
modint y = 10;
int z = 1234;
y * z;

@{keyword.constraints}

  • gcd(b.val(), mod) == 1 should be satisfied when evaluating a / b (or a /= b).

@{keyword.complexity}

  • O(1)O(1) (all operations except division)
  • O(log⁡mod)O(\log \mathrm{mod}) (division)

pow

C++
modint x.pow(ll n)

It returns xnx^n.

@{keyword.constraints}

  • 0≤n0 \le n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

inv

C++
modint x.inv()

It returns yy with xy≡1xy \equiv 1.

@{keyword.constraints}

  • gcd(x.val(), mod) = 1

@{keyword.complexity}

  • O(log⁡mod)O(\log \mathrm{mod})

raw

C++
modint modint::raw(int x)

It returns modint(x) without taking mod. It is the function for constant-factor speedup.

For example, the following code works even if i is greater than or equal to mod, because mod is automatically taken.

C++
modint a;
int i;
a += i;

However, in the following code, it is ensured that i is less than mod.

C++
int main() {
    modint::set_mod(1000000007);
    modint a = 1;
    for (int i = 1; i < 100000; i++) {
        a += i;
    }
}

In such a situation, we can decrease the number of mod operations as follows.

C++
int main() {
    modint::set_mod(1000000007);
    modint a = 1;
    for (int i = 1; i < 100000; i++) {
        a += modint::raw(i);
    }
}

When the value more than or equal to mod is assigned to modint::raw(x), the behavior is undefined.

@{keyword.constraints}

  • 0≤x<mod0 \leq x \lt \mathrm{mod}

Tips (other mod)

You can use the other fixed mod like 1000000009 as follows.

C++
using mint = static_modint<1000000009>;

modint998244353 (resp. modint1000000007) is the alias of static_modint<998244353> (resp. static_modint<1000000007>).

C++
using modint998244353 = static_modint<998244353>;
using modint1000000007 = static_modint<1000000007>;

Tips (multiple mods)

You can use multiple mods as follows.

C++
using mint0 = dynamic_modint<0>;
using mint1 = dynamic_modint<1>;

modint is the alias of dynamic_modint<-1>.

C++
using modint = dynamic_modint<-1>;

SCC

It calculates the strongly connected components of directed graphs.

Constructor

C++
scc_graph graph(int n)

It creates a directed graph with nn vertices and 00 edges.

@{keyword.constraints}

  • 0≤n≤1080 \leq n \leq 10^8

@{keyword.complexity}

  • O(n)O(n)

add_edge

C++
void graph.add_edge(int from, int to)

It adds a directed edge from the vertex from to the vertex to.

@{keyword.constraints}

  • 0≤from<n0 \leq \mathrm{from} \lt n
  • 0≤to<n0 \leq \mathrm{to} \lt n

@{keyword.complexity}

  • O(1)O(1) amortized

scc

C++
vector<vector<int>> graph.scc()

It returns the list of the “list of the vertices” that satisfies the following.

  • Each vertex is in exactly one “list of the vertices”.
  • Each “list of the vertices” corresponds to the vertex set of a strongly connected component. The order of the vertices in the list is undefined.
  • The list of “list of the vertices” are sorted in topological order, i.e., for two vertices u,vu, v in different strongly connected components, if there is a directed path from uu to vv, the list containing uu appears earlier than the list containing vv.

@{keyword.complexity}

  • O(n+m)O(n + m), where mm is the number of added edges.

Segtree

It is the data structure for monoids (S,⋅:S×S→S,e∈S)(S, \cdot: S \times S \to S, e \in S), i.e., the algebraic structure that satisfies the following properties.

  • associativity: (a⋅b)⋅c(a \cdot b) \cdot c = a⋅(b⋅c)a \cdot (b \cdot c) for all a,b,c∈Sa, b, c \in S
  • existence of the identity element: a⋅ea \cdot e = e⋅ae \cdot a = aa for all a∈Sa \in S

Given an array SS of length NN, it processes the following queries in O(log⁡N)O(\log N) time (see Appendix for further details).

  • Updating an element
  • Calculating the product of the elements of an interval

For simplicity, in this document, we assume that the oracles op and e work in constant time. If these oracles work in O(T)O(T) time, each time complexity appear in this document is multipled by O(T)O(T).

Constructor

C++
(1) segtree<S, op, e> seg(int n)
(2) segtree<S, op, e> seg(vector<S> v)

The following should be defined.

  • The type S
  • The binary operation S op(S a, S b)
  • The identity element S e()

For example, for Range Minimum Query, the definitions are as follows.

C++
int op(int a, int b) {
    return min(a, b);
}

int e() {
    return (int)(1e9);
}

segtree<int, op, e> seg(10);
  • (1): It creates an array a of length n. All the elements are initialized to e().
  • (2): It creates an array a of length n = v.size(), initialized to v.

See examples and here for further details.

@{keyword.constraints}

  • 0≤n≤1080 \leq n \leq 10^8

@{keyword.complexity}

  • O(n)O(n)

set

C++
void seg.set(int p, S x)

It assigns xx to a[p].

@{keyword.constraints}

  • 0≤p<n0 \leq p < n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

get

C++
S seg.get(int p)

It returns a[p].

@{keyword.constraints}

  • 0≤p<n0 \leq p < n

@{keyword.complexity}

  • O(1)O(1)

prod

C++
S seg.prod(int l, int r)

It returns op(a[l], ..., a[r - 1]), assuming the properties of the monoid. It returns e() if l=rl = r.

@{keyword.constraints}

  • 0≤l≤r≤n0 \leq l \leq r \leq n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

all_prod

C++
S seg.all_prod()

It returns op(a[0], ..., a[n - 1]), assuming the properties of the monoid. It returns e() if n=0n = 0.

@{keyword.complexity}

  • O(1)O(1)

max_right

C++
(1) int seg.max_right<f>(int l)
(2) int seg.max_right<F>(int l, F f)
  • (1): It applies binary search on the segment tree. The function bool f(S x) should be defined.
  • (2): The function object that takes S as the argument and returns bool should be defined.

It returns an index r that satisfies both of the following.

  • r = l or f(op(a[l], a[l + 1], ..., a[r - 1])) = true
  • r = n or f(op(a[l], a[l + 1], ..., a[r])) = false

If f is monotone, this is the maximum r that satisfies f(op(a[l], a[l + 1], ..., a[r - 1])) = true.

@{keyword.constraints}

  • if f is called with the same argument, it returns the same value, i.e., f has no side effect.
  • f(e()) = true
  • 0≤l≤n0 \leq l \leq n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

min_left

C++
(1) int seg.min_left<f>(int r)
(2) int seg.min_left<F>(int r, F f)
  • (1): It applies binary search on the segment tree. The function bool f(S x) should be defined.
  • (2): The function object that takes S as the argument and returns bool should be defined.

It returns an index l that satisfies both of the following.

  • l = r or f(op(a[l], a[l + 1], ..., a[r - 1])) = true
  • l = 0 or f(op(a[l - 1], a[l], ..., a[r - 1])) = false

If f is monotone, this is the minimum l that satisfies f(op(a[l], a[l + 1], ..., a[r - 1])) = true.

@{keyword.constraints}

  • if f is called with the same argument, it returns the same value, i.e., f has no side effect.
  • f(e()) = true
  • 0≤r≤n0 \leq r \leq n

@{keyword.complexity}

  • O(log⁡n)O(\log n)

String

It contains string algorithms.

Let s be a string. We denote the substring of s between aa-th and b−1b - 1-th character by s[a..b).

suffix_array

C++
(1) vector<int> suffix_array(string s)
(2) vector<int> suffix_array<T>(vector<T> s)
(3) vector<int> suffix_array(vector<int> s, int upper)

Given a string s of length nn, it returns the suffix array of s. Here, the suffix array sa of s is a permutation of 0,⋯ ,n−10, \cdots, n-1 such that s[sa[i]..n) < s[sa[i+1]..n) holds for all i=0,1,⋯ ,n−2i = 0,1, \cdots ,n-2.

@{keyword.constraints}

  • 0≤n≤1080 \leq n \leq 10^8
  • (2) T is int, uint, ll, or ull.
  • (3) 0≤upper≤1080 \leq \mathrm{upper} \leq 10^8
  • (3) 0≤x≤upper0 \leq x \leq \mathrm{upper} for all elements xx of ss.

Complexity

  • (1) O(n)O(n)-time
  • (2) O(nlog⁡n)O(n \log n)-time, O(n)O(n)-space
  • (3) O(n+upper)O(n + \mathrm{upper})-time

lcp_array

C++
(1) vector<int> lcp_array(string s, vector<int> sa)
(2) vector<int> lcp_array<T>(vector<T> s, vector<int> sa)

Given a string s of length nn, it returns the LCP array of s. Here, the LCP array of s is the array of length n−1n-1, such that the ii-th element is the length of the LCP (Longest Common Prefix) of s[sa[i]..n) and s[sa[i+1]..n).

@{keyword.constraints}

  • sa is the suffix array of s.
  • 1≤n≤1081 \leq n \leq 10^8
  • (2): T is int, uint, ll, or ull.

@{keyword.complexity}

  • O(n)O(n)

z_algorithm

C++
(1) vector<int> z_algorithm(string s)
(2) vector<int> z_algorithm<T>(vector<T> s)

Given a string of length nn, it returns the array of length nn, such that the ii-th element is the length of the LCP (Longest Common Prefix) of s[0..n) and s[i..n).

@{keyword.constraints}

  • 0≤n≤1080 \leq n \leq 10^8
  • (2): T is int, uint, ll, or ull

@{keyword.complexity}

  • O(n)O(n)

2-SAT

It solves 2-SAT.

For variables x0,x1,⋯ ,xN−1x_0, x_1, \cdots, x_{N - 1} and clauses with form

  • (xi=f)∨(xj=g)(x_i = f) \lor (x_j = g),

it decides whether there is a truth assignment that satisfies all clauses.

Constructor

C++
two_sat ts(int n)

It creates a 2-SAT of nn variables and 00 clauses.

@{keyword.constraints}

  • 0≤n≤1080 \leq n \leq 10^8

@{keyword.complexity}

  • O(n)O(n)

add_clause

C++
void ts.add_clause(int i, bool f, int j, bool g)

It adds a clause (xi=f)∨(xj=g)(x_i = f) \lor (x_j = g).

@{keyword.constraints}

  • 0≤i<n0 \leq i \lt n
  • 0≤j<n0 \leq j \lt n

@{keyword.complexity}

  • O(1)O(1) amortized

satisfiable

C++
bool ts.satisfiable()

If there is a truth assignment that satisfies all clauses, it returns true. Otherwise, it returns false.

@{keyword.constraints}

  • You may call it multiple times.

@{keyword.complexity}

  • O(n+m)O(n + m), where mm is the number of added clauses.

answer

C++
vector<bool> ts.answer()

It returns a truth assignment that satisfies all clauses of the last call of satisfiable. If we call it before calling satisfiable or when the last call of satisfiable returns false, it returns the vector of length nn with undefined elements.

@{keyword.complexity}

  • O(n)O(n)
原文