text
stringlengths
2
104M
meta
dict
# ModInt This is a library that can be used for problems where the answer is divided by a certain number and the remainder is output. It automatically takes the remainder when calculating, thus reducing errors. ## Caution The use of this library ModInt may slow down the execution time. Please be careful when using it. ## Example usage First, set the remainder law with `ModInt.set_mod` or `ModInt.mod =`. ```ruby ModInt.set_mod(11) ModInt.mod #=> 11 a = ModInt(10) b = 3.to_m p -b # 8 mod 11 p a + b # 2 mod 11 p 1 + a # 0 mod 11 p a - b # 7 mod 11 p b - a # 4 mod 11 p a * b # 8 mod 11 p b.inv # 4 mod 11 p a / b # 7 mod 11 a += b p a # 2 mod 11 a -= b p a # 10 mod 11 a *= b p a # 8 mod 11 a /= b p a # 10 mod 11 p ModInt(2)**4 # 5 mod 11 puts a #=> 10 p ModInt.raw(3) #=> 3 mod 11 ``` ## output with puts and p ```ruby ModInt.mod = 11 a = 12.to_m puts a #=> 1 p a #=> 1 mod 11 ``` `ModInt` defines `to_s` and `inspect`. This causes `puts` to use `to_s` and `p` to use `inspect` internally, so the output is modified. Note that the `puts` method is useful because it behaves no differently than the output of `Integer`, but conversely, it is indistinguishable. ## Singular methods. ### new(val = 0) -> ModInt ```ruby a = ModInt.new(10) b = ModInt(3) ``` We have a syntax sugar `Kernel#ModInt` that does not use `new`. #### [Reference] Integer#to_m, String#to_m ```ruby 5.to_m '2'.to_m ``` Converts `Integer` and `String` instances to `ModInt`. **aliases** `to_modint`, `to_m`. ### set_mod(mod) ```ruby ModInt.set_mod(10**9 + 7) ModInt.mod = 10**9 + 7 ``` Use this method first to set the mod. This is set to the global variable `$_mod` as an internal implementation. It also internally checks whether `$_mod` is prime or not, and assigns a boolean value to the global variable `$_mod_is_prime`. Note that you may not have many chances to use the return value of this method, but `mod=` returns the assigned argument as it is, while `set_mod` returns `[mod, mod.prime?] **aliases** `set_mod`, `mod=` ### mod -> Integer ```ruby ModInt.mod ``` Returns mod. This returns the global variable `$_mod` as an internal implementation. ### raw(val) -> ModInt Returns ````ruby ModInt.raw(2, 11) # 2 mod 11 ```` Returns ModInt instead of taking mod for `val`. This is a constructor for constant-fold speedup. If `val` is guaranteed to be greater than or equal to `0` and not exceed `mod`, it is faster to generate `ModInt` here. ## Instance Methods ### val -> Integer ```ruby ModInt.mod = 11 m = 12.to_m # 1 mod 11 n = -1.to_m # 10 mod 11 p i = m.val #=> 1 p j = n.to_i #=> 10 ``` Returns the value of the body from an instance of the ModInt class. As an internal implementation, it returns `@val`. Use it to convert to `integer`. **Aliases** - `val` - `to_i`. #### Additional information about aliases There is no difference between `val` and `to_i` as an alias for the instance method of `ModInt`. However, the `Integer` class also has a `to_i` method, so `to_i` is more flexible and Ruby-like. In the internal implementation, `to_i` is used so that either argument can be used. Note that `val` is the name of the function in the original, and `@val` is the name of the instance variable in the internal implementation. ### inv -> ModInt ```rb ModInt.mod = 11 m = 3.to_m p m.inv #=> 4 mod 11 ``` It returns `y` such that `xy ≡ 1 (mod ModInt.mod)`. That is, it returns the modulus inverse. ### pow(other) -> ModInt ```ruby ModInt.mod = 11 m = 2.to_m p m**4 #=> 5 mod 11 p m.pow(4) #=> 5 mod 11 ``` Only `integer` can be taken as argument. ### Various operations. As with the `Integer` class, you can perform arithmetic operations between `ModInt` and `Integer`, or between `Integer` and `ModInt`. See the usage examples for details. ```ruby ModInt.mod = 11 p 5.to_m + 7.to_m #=> 1 mod 11 p 0 + -1.to_m #=> 10 mod 11 p -1.to_m + 0 #=> 10 mod 11 p 12.to_m == 23.to_m #=> true p 12.to_m == 1 #=> true ``` #### [Note] How to compare Integer and ModInt `Integer` and `ModInt` can be compared by `==`, `! =`, but some behaviors are different from the original ACL. The `Integer` to be compared returns true or false in the range of [0, mod), but always returns `false` in other ranges. This library has a restriction in the range of [0, mod), but the original library does not, so it differs in this point. ## Verified - [ABC156: D - Bouquet](https://atcoder.jp/contests/abc156/tasks/abc156_d) held on 2020/2/22 - [AC Code 138ms 2020/10/5](https://atcoder.jp/contests/abc156/submissions/17205940) - [ARC009: C - Takahashi, 24 years old](https://atcoder.jp/contests/arc009/tasks/arc009_3) held on 2012/10/20 - [AC Code 1075ms 2020/10/5](https://atcoder.jp/contests/arc009/submissions/17206081) - [AC code 901ms 2020/10/5](https://atcoder.jp/contests/arc009/submissions/17208378) ## Speedup Tips. The methods `+`, `-`, `*`, and `/` use the methods `add!`, `sub!`, `mul!`, and `div!` for the ones that are internally duplicated with `dup`, respectively. If you can destructively change the receiver's `ModInt`, this method may be faster on a constant-duple basis. ## Reference links - This library - [The code of this library modint.rb(GitHub)](https://github.com/universato/ac-library-rb/blob/main/lib/modint.rb) - Our library [Our code modint_test.rb(GitHub)](https://github.com/universato/ac-library-rb/blob/main/lib/modint.rb) - The original library - [Our implementation code modint.hpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/atcoder/modint.hpp) - Test code of the main library [modint_test.cpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/atcoder/modint.hpp) - Documentation of the original modint.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_ja/modint.md) - Ruby Reference Manual - [class Numeric \(Ruby 2\.7\.0 Reference Manual\)](https://docs.ruby-lang.org/ja/latest/class/Numeric.html) - Others - [Why don't you try using the modint struct? \(C\cH000000)}Noshi91's Notes](https://noshi91.hatenablog.com/entry/2019/03/31/174006)(Mar 31, 2019) - [Implementing modint in Python - Qiita](https://qiita.com/wotsushi/items/c936838df992b706084c)(Apr 1, 2019) - [Documentation of the C# version of ModInt](https://github.com/key-moon/ac-library-cs/blob/main/document_ja/modint.md) ## Q&A. ### Why include it if it may slow down the execution time? - Reproduction of the original library. - Reproduction to the essential part of the code. - To measure how slow it really is. As a benchmark. - To increase the number of users, to check the demand, and to appeal for inclusion in Ruby itself. ### Advantages of ModInt Ruby, unlike C/C++, has the following features. - Definition of a negative number divided by a positive number that still returns a positive number - Multiple length integers, no overflow (* If the number is too large, the calculation becomes slower) Therefore, compared to C/C++, the advantages of using ModInt are diminished in some areas, but - Improved readability - There is no need to worry about forgetting to take ModInt. The following are some of the advantages. ### The intention of using global variables is We are using global variables `$_mod` and `$_mod_is_prime`. Global variables are to be avoided, especially in practice. Translated with www.DeepL.com/Translator (free version)
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# index | C | D | | | :--- | :--- | --- | | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/fenwick_tree.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/fenwick_tree.md) |FenwickTree(BIT)| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/segtree.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/segtree.md) |Segtree| | [○](https://github.com/universato/ac-library-rb/blob/main/lib/lazy_segtree.rb) | [○G](https://github.com/universato/ac-library-rb/blob/main/document_ja/lazy_segtree.md) |LazySegtree| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/priority_queue.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/priority_queue.md) |PriorityQueue| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/suffix_array.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/string.md) |suffix_array| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/lcp_array.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/string.md) |lcp_array| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/z_algorithm.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/string.md) |z_algorithm| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/pow_mod.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/math.md) |pow_mod| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/inv_mod.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/math.md) |inv_mod| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/crt.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/math.md) |crt(Chinese remainder theorem)| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/floor_sum.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/math.md) |floor_sum| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/convolution.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/convolution.md) |convolution| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/modint.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/modint.md) |ModInt| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/dsu.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/dsu.md) |DSU(UnionFind)| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/max_flow.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/max_flow.md) |MaxFlow| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/min_cost_flow.rb) |[◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/min_cost_flow.md) |MinCostFlow| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/scc.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/scc.md) |SCC (Strongly Connected Component)| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/two_sat.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/two_sat.md) |TwoSat| ## Link to Code on GitHub ### Data structure - [fenwick_tree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/fenwick_tree.rb) - [segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/segtree.rb) - [lazy_segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/lazy_segtree.rb) - [priority_queue.rb](https://github.com/universato/ac-library-rb/blob/main/lib/priority_queue.rb) - String - [suffix_array.rb](https://github.com/universato/ac-library-rb/blob/main/lib/suffix_array.rb) - [lcp_array.rb](https://github.com/universato/ac-library-rb/blob/main/lib/lcp_array.rb) - [z_algorithm.rb](https://github.com/universato/ac-library-rb/blob/main/lib/z_algorithm.rb) ### Math - math - [pow_mod.rb](https://github.com/universato/ac-library-rb/blob/main/lib/pow_mod.rb) - [inv_mod.rb](https://github.com/universato/ac-library-rb/blob/main/lib/inv_mod.rb) - [crt.rb](https://github.com/universato/ac-library-rb/blob/main/lib/crt.rb) - [floor_sum.rb](https://github.com/universato/ac-library-rb/blob/main/lib/floor_sum.rb) - [convolution.rb](https://github.com/universato/ac-library-rb/blob/main/lib/convolution.rb) - [modint.rb](https://github.com/universato/ac-library-rb/blob/main/lib/modint.rb) ### Graph - [dsu.rb](https://github.com/universato/ac-library-rb/blob/main/lib/dsu.rb) - [max_flow.rb](https://github.com/universato/ac-library-rb/blob/main/lib/max_flow.rb) - [min_cost_flow.rb](https://github.com/universato/ac-library-rb/blob/main/lib/min_cost_flow.rb) - [scc.rb](https://github.com/universato/ac-library-rb/blob/main/lib/scc.rb) - [two_sat.rb](https://github.com/universato/ac-library-rb/blob/main/lib/two_sat.rb) ## Alphabet Order Index <details> <summary>Alphabet Order Index</summary> [convolution.rb](https://github.com/universato/ac-library-rb/blob/main/lib/convolution.rb) [crt.rb](https://github.com/universato/ac-library-rb/blob/main/lib/crt.rb) [dsu.rb](https://github.com/universato/ac-library-rb/blob/main/lib/dsu.rb) [fenwick_tree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/fenwick_tree.rb) [floor_sum.rb](https://github.com/universato/ac-library-rb/blob/main/lib/floor_sum..rb) [inv_mod.rb](https://github.com/universato/ac-library-rb/blob/main/lib/inv_mod.rb) [lazy_segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/lazy_segtree.rb) [lcp_array.rb](https://github.com/universato/ac-library-rb/blob/main/lib/lcp_array.rb) [max_flow.rb](https://github.com/universato/ac-library-rb/blob/main/lib/max_flow.rb) [min_cost_flow.rb](https://github.com/universato/ac-library-rb/blob/main/lib/min_cost_flow.rb) [modint.rb](https://github.com/universato/ac-library-rb/blob/main/lib/modint.rb) [pow_mod.rb](https://github.com/universato/ac-library-rb/blob/main/lib/pow_mod.rb) [priority_queue.rb](https://github.com/universato/ac-library-rb/blob/main/lib/priority_queue.rb) [scc.rb](https://github.com/universato/ac-library-rb/blob/main/lib/scc.rb) [segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/segtree.rb) [suffix_array.rb](https://github.com/universato/ac-library-rb/blob/main/lib/suffix_array.rb) [two_sat.rb](https://github.com/universato/ac-library-rb/blob/main/lib/two_sat.rb) [z_algorithm.rb](https://github.com/universato/ac-library-rb/blob/main/lib/z_algorithm.rb) </details>
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Fenwick Tree **alias: BIT (Binary Indexed Tree)** Given an array of length `N`, it processes the following queries in `O(log N)` time. - Updating an element - Calculating the sum of the elements of an interval ## Class Method ### new(n) -> FenwickTree ```rb fw = FenwickTree.new(5) ``` It creates an array `a_0, a_1, ...... a_{n-1}` of length `n`. All the elements are initialized to `0`. **complexity** - `O(n)` ### new(ary) -> FenwickTree ```rb fw = FenwickTree.new([1, 3, 2]) ``` It creates an array `ary`. **complexity** - `O(n)` ## add(pos, x) ```rb fw.add(pos, x) ``` It processes `a[p] += x`. `pos` is zero-based index. **constraints** - `0 ≊ pos < n` **complexity** - `O(log n)` ## sum(l, r) ->Integer ```rb fw.sum(l, r) ``` It returns `a[l] + a[l + 1] + ... + a[r - 1]`. It equals `fw._sum(r) - fw._sum(l)` **constraints** - `0 ≊ l ≩ r ≩ n` **complexity** - `O(log n)` ## _sum(pos) -> Integer ```rb fw._sum(pos) ``` It returns `a[0] + a[1] + ... + a[pos - 1]`. **complexity** - `O(logn)` ## Verified - [AtCoder ALPC B - Fenwick Tree](https://atcoder.jp/contests/practice2/tasks/practice2_b) - [AC Code(1272ms)](https://atcoder.jp/contests/practice2/submissions/17074108) - [F - Range Xor Query](https://atcoder.jp/contests/abc185/tasks/abc185_f) - [AC Code(821ms)](https://atcoder.jp/contests/abc185/submissions/18769200) ## Link - ac-library-rb - [Code dsu.rb](https://github.com/universato/ac-library-rb/blob/main/lib/dsu.rb) - [Test dsu_test.rb](https://github.com/universato/ac-library-rb/blob/main/test/dsu_test.rb) - AtCoder - [fenwicktree.html](https://atcoder.github.io/ac-library/document_en/fenwicktree.html) - [Code fenwick.hpp](https://github.com/atcoder/ac-library/blob/master/atcoder/fenwick.hpp)
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# LazySegtree This is a lazy evaluation segment tree. ## Class Methods ### new(v, e, id, op, mapping, composition) ```ruby seg = LazySegtree.new(v, e, id, op, mapping, compositon) ``` The first argument can be an `Integer` or an `Array`. - If the first argument is an `Integer` of `n`, a segment tree of length `n` and initial value `e` will be created. - If the first argument is `a` of `Array` with length `n`, a segment tree will be created based on `a`. The second argument `e` is the unit source. We need to define the monoid by defining the binary operation `op(x, y)` in the block. **Complexity** - `O(n)` ## Instance methods ## set(pos, x) ```ruby seg.set(pos, x) ``` Assign `x` to `a[pos]`. **Complexity** - `O(logn)` ### get(pos) -> same class as unit source e ```ruby seg.get(pos) ``` It returns `a[pos]`. **Complexity** - `O(1)` ### prod(l, r) -> same class as unit source e ```ruby seg.prod(l, r) ``` It returns `op(a[l], ... , a[r - 1])`. **Constraints** - `0 ≀ l ≀ r ≀ n`. **Complexity** - `O(logn)` ### all_prod -> same class as unit source e ```ruby seg.all_prod ``` It returns `op(a[0], ... , a[n - 1])`. **Complexity** - `O(1)`. ### apply(pos, val) ```ruby seg.apply(pos, val) ``` The implementation with three arguments in the original code is called `range_apply` in this library. If it looks OK after measuring the execution time, we can make the `apply` method support both 2 and 3 arguments. **Constraints** - `0 ≀ pos < n`. **Complexity** - `O(log n)`. ### range_apply(l, r, val) ```ruby seg.range_apply(l, r, val) ``` **Constraints** - `0 ≀ l ≀ r ≀ n`. **Complexity** - `O(log n)` ### max_right(l){ } -> Integer It applies binary search on the LazySegtree. **Constraints** - `0 ≩ l ≩ n` **Complexity** - `O(log n)` ### min_left(r){ } -> Integer It applies binary search on the LazySegtree. **Constraints** - `0 ≩ r ≩ n` **Complexity** - `O(log n)` ## Verified This is the link in question. There is no code, but it has been Verified. - [AIZU ONLINE JUDGE DSL\_2\_F RMQ and RUQ](http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_F) - [AIZU ONLINE JUDGE DSL\_2\_G RSQ and RAQ](http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_G) The following problem is not AC in Ruby because the execution time is strictly TLE. - [ALPC: K - Range Affine Range Sum](https://atcoder.jp/contests/practice2/tasks/practice2_k) - [ALPC: L - Lazy Segment Tree](https://atcoder.jp/contests/practice2/tasks/practice2_l) ## Reference links - ac-library-rb - [Code: lazy_segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/lazy_segtree.rb) - [Test code: lazy_segtree_test.rb](https://github.com/universato/ac-library-rb/blob/main/test/lazy_segtree_test.rb) - AtCoder Library - [Document: lazysegtree.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_en/lazysegtree.md) - [Documentat: appendix.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_en/appendix.md) - [Code: lazysegtree.hpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp) - [Test code: lazysegtree_test.cpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/test/unittest/lazysegtree_test.cpp ) ## Differences from the original library. ### Not `ceil_pow2`, but `bit_length`. The original C++ library uses the original `internal::ceil_pow2` function, but this library uses the existing Ruby method `Integer#bit_length`. This library uses the existing Ruby method `Integer#bit_length`, which is faster than the original method.
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# PriorityQueue PriorityQueue **Alias** - `HeapQueue` ## Class Methods ### new(array = []) -> PriorityQueue ```ruby PriorityQueue.new pq = PriorityQueue.new([1, -1, 100]) pq.pop # => 100 pq.pop # => 1 pq.pop # => -1 ``` It creates a `PriorityQueue` to initialized to `array`. **Complexity** - `O(n)` (`n` is the number of elements of `array`) ### new(array = []) {|x, y| ... } -> PriorityQueue ```ruby PriorityQueue.new([1, -1, 100]) {|x, y| x < y } pq.pop # => -1 pq.pop # => 1 pq.pop # => 100 ``` Constructs a prioritized queue from an array given as an argument. A comparison function can be passed in the block. When a comparison function is passed, it is used to calculate the priority of the elements. Any object can be an element of the queue if it can be compared with the comparison function. **Complexity** - `O(n)` (`n` is the number of elements of `array`) ## Instance Methods ### push(item) ```ruby pq.push(10) ``` It adds the element. **Alias** - `<<` - `append` **Complexity** - `O(log n)` (`n` is the number of elements of priority queue) ### pop -> Highest priority element | nil ```ruby pq.pop # => 100 ``` It removes the element with the highest priority from the queue and returns it. If the queue is empty, it rerurns `nil`. **Complexity** - `O(log n)` (`n` is the number of elements of priority queue) ### get -> Highest priority element | nil ```ruby pq.get # => 10 ``` It returns the value of the highest priority element without removing it. If the queue is empty, it returns `nil`. **Alias** - `top` **Complexity** - `O(1)` ### empty? -> bool ```ruby pq.empty? # => false ``` It returns `true` if the queue is empty, `false` otherwise. **Complexity** `O(1)` ### heap -> Array[elements of priority queue] ```ruby pq.heap ``` It returns the binary heap that the priority queue has internally. ## Verified - [Aizu Online Judge ALDS1_9_C Priority Queue](https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_9_C) - [AC code](https://onlinejudge.u-aizu.ac.jp/solutions/problem/ALDS1_9_C/review/4835681/qsako6/Ruby) ## Links - [cpython/heapq.py at main - python/cpython](https://github.com/python/cpython/blob/main/Lib/heapq.py)
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# DSU - Disjoint Set Union **alias: Union Find** Given an undirected graph, it processes the following queries in `O(α(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. ## Usage ```rb d = DSU.new(5) p d.groups # => [[0], [1], [2], [3], [4]] p d.same?(2, 3) # => false p d.size(2) # => 1 d.merge(2, 3) p d.groups # => [[0], [1], [2, 3], [4]] p d.same?(2, 3) # => true p d.size(2) # => 2 ``` ## Class Method ### new(n) -> DSU ```rb d = DSU.new(n) ``` It creates an undirected graph with `n` vertices and `0` edges. **complexity** - `O(n)` **alias** - `DSU`, `UnionFind` ## Instance Methods ### merge(a, b) -> Integer ```rb d.merge(a, b) ``` It adds an edge $(a, b)$. If the vertices $a$ and $b$ were in the same connected component, it returns the representative of this connected component. Otherwise, it returns the representative of the new connected component. **complexity** - `O(α(n))` amortized **alias** - `merge`, `unite` ### same?(a, b) -> bool ```rb d.same?(a, b) ``` It returns whether the vertices `a` and `b` are in the same connected component. **complexity** - `O(α(n))` amortized **alias** - `same?`, `same` ### leader(a) -> Integer ```rb d.leader(a) ``` It returns the representative of the connected component that contains the vertex `a`. **complexity** - `O(α(n))` amortized **alias** - `leader`, `root`, `find` ### size(a) -> Integer It returns the size of the connected component that contains the vertex `a`. **complexity** - `O(α(n))` amortized ### groups -> Array(Array(Integer)) ```rb 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. **complexity** - `O(α(n))` amortized ## Verified [A - Disjoint Set Union](https://atcoder.jp/contests/practice2/tasks/practice2_a) ## Links & Reference - ac-library-rb - [Code dsu.rb](https://github.com/universato/ac-library-rb/blob/main/lib/dsu.rb) - [Test dsu_test.rb](https://github.com/universato/ac-library-rb/blob/main/test/dsu_test.rb) - AtCoder Library - [Document](https://github.com/atcoder/ac-library/blob/master/document_en/dsu.md) - [Code dsu.hpp](https://github.com/atcoder/ac-library/blob/master/atcoder/dsu.hpp)
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Segtree Segment Tree ## Class Methods ### new(n, e){ |x, y| ... } -> Segtree ### new(n, op, e) -> Segtree ```rb seg = Segtree.new(n, e) { |x, y| ... } ``` It creates an array `a` of length `n`. All the elements are initialized to `e`. - `block`: returns `op(x, y)` - `e`: identity element. ### new(ary, e){ |x, y| ... } -> Segtree ### new(ary, op, e) -> Segtree ```rb seg = Segtree.new(ary, e) { |x, y| ... } ``` It creates an array `seg` of length `n` = `ary.size`, initialized to `ary`. - `block`: returns `op(x, y)` - `e`: identity element. **complexty** - `O(n)` <details> <summary>Monoid Exmaples</summary> ```rb n = 10**5 inf = (1 << 60) - 1 Segtree.new(n, 0) { |x, y| x.gcd y } # gcd Segtree.new(n, 1) { |x, y| x.lcm y } # lcm Segtree.new(n, -inf) { |x, y| [x, y].max } # max Segtree.new(n, inf) { |x, y| [x, y].min } # min Segtree.new(n, 0) { |x, y| x | y } # or Segtree.new(n, 1) { |x, y| x * y } # prod Segtree.new(n, 0) { |x, y| x + y } # sum ``` </details> ## Instance Methods ### set ```rb seg.set(pos, x) ``` It assigns `x` to `a[pos]`. **Complexity** `O(logn)` ### get ```rb seg.get(pos) ``` It returns `a[pos]` **Complexity** `O(1)` ### prod ```rb seg.prod(l, r) ``` It returns `op(a[l], ..., a[r - 1])` . **Constraints** - `0 ≩ l ≩ r ≩ n` **Complexity** - `O(logn)` ### all_prod ```rb seg.all_prod ``` It returns `op(a[0], ..., a[n - 1])`. **Complexity** - `O(1)` ### max_right(l, &f) -> Integer ```ruby seg.max_right(l, &f) ``` It applies binary search on the segment tree. It returns an index `r` that satisfies both of the following. - `r = l` or `f(prod(l, r)) = true` - `r = n` or `f(prod(l, r + 1)) = false` **Constraints** - `f(e) = true` - `0 ≩ l ≩ n` **Complexity** - `O(log n)` ### min_left(r, &f) -> Integer ```ruby seg.min_left(r, &f) ``` It applies binary search on the segment tree. It returns an index l that satisfies both of the following. - `l = r` or `f(prod(l, r)) = true` - `l = 0` or `f(prod(l - 1, r)) = false` **Constraints** - `f(e) = true` - `0 ≩ r ≩ n` **Complexity** - `O(log n)` ## Verified - [ALPC: J - Segment Tree](https://atcoder.jp/contests/practice2/tasks/practice2_j) - [AC Code(884ms) max_right](https://atcoder.jp/contests/practice2/submissions/23196480) - [AC Code(914ms) min_left](https://atcoder.jp/contests/practice2/submissions/23197311) - [F - Range Xor Query](https://atcoder.jp/contests/abc185/tasks/abc185_f) - [AC Code(1538ms)](https://atcoder.jp/contests/abc185/submissions/18746817): Segtree(xor) - [AC Code(821ms)](https://atcoder.jp/contests/abc185/submissions/18769200): FenwickTree(BIT) xor ## 参考リンク - ac-library - [Code segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/segtree.rb) - [Test segtree_test.rb](https://github.com/universato/ac-library-rb/blob/main/test/segtree_test.rb) - AtCoder Library - [Document HTML](https://atcoder.github.io/ac-library/document_en/segtree.html) - [Documetn appendix.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_en/appendix.md) - [Code segtree.hpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/atcoder/segtree.hpp) - [Test segtree_test.cpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/test/unittest/segtree_test.cpp) - [Sample code segtree_practice.cpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/test/example/segtree_practice.cpp)
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
require 'pathname' # copy libraries from `lib` to `lib_lock/ac-library` and add `module AcLibraryRb` lib_path = File.expand_path('../lib/**', __dir__) lock_dir = File.expand_path('../lib_lock/ac-library-rb', __dir__) Dir.glob(lib_path) do |file| next unless FileTest.file?(file) path = Pathname.new(lock_dir) + Pathname.new(file).basename File.open(path, "w") do |f| library_code = File.readlines(file).map{ |line| line == "\n" ? "\n" : ' ' + line } f.puts "module AcLibraryRb" f.puts library_code f.puts "end" end end # copy library from `lib/core_ext` to `lib_lock/ac-library-rb/core_ext` ac_library_rb_classes = %w[ModInt FenwickTree PriorityQueue] replaces = ac_library_rb_classes.to_h{ |cls| ["#{cls}.new", "AcLibraryRb::#{cls}.new"] } pattern = Regexp.new(replaces.keys.join('|')) lib_path = File.expand_path('../lib/core_ext/**', __dir__) lock_dir = File.expand_path('../lib_lock/ac-library-rb/core_ext', __dir__) Dir.glob(lib_path) do |file| next unless FileTest.file?(file) path = Pathname.new(lock_dir) + Pathname.new(file).basename File.open(path, "w") do |f| f.puts File.readlines(file).map{ |text| text.gsub(pattern, replaces) } end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' set -vx bundle install # Do any other automated setup that you need to do here
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
#!/usr/bin/env ruby require "bundler/setup" require_relative "../lib_helpers/ac-library-rb/all.rb" require "irb" IRB.start(__FILE__)
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # Fenwick Tree class FenwickTree attr_reader :data, :size def initialize(arg) case arg when Array @size = arg.size @data = [0].concat(arg) (1 ... @size).each do |i| up = i + (i & -i) next if up > @size @data[up] += @data[i] end when Integer @size = arg @data = Array.new(@size + 1, 0) else raise ArgumentError.new("wrong argument. type is Array or Integer") end end def add(i, x) i += 1 while i <= @size @data[i] += x i += (i & -i) end end # .sum(l, r) # [l, r) <- Original # .sum(r) # [0, r) <- [Experimental] # .sum(l..r) # [l, r] <- [Experimental] def sum(a, b = nil) if b _sum(b) - _sum(a) elsif a.is_a?(Range) l = a.begin l += @size if l < 0 if r = a.end r += @size if r < 0 r += 1 unless a.exclude_end? else r = @size end _sum(r) - _sum(l) else _sum(a) end end def _sum(i) res = 0 while i > 0 res += @data[i] i &= i - 1 end res end alias left_sum _sum def to_s "<#{self.class}: @size=#{@size}, (#{@data[1..].join(', ')})>" end end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # Segment tree with Lazy propagation class LazySegtree attr_reader :d, :lz, :e, :id attr_accessor :op, :mapping, :composition # new(v, op, e, mapping, composition, id) # new(v, e, id, op, mapping, composition) # new(v, e, id){ |x, y| } def initialize(v, a1, a2, a3 = nil, a4 = nil, a5 = nil, &op_block) if a1.is_a?(Proc) @op, @e, @mapping, @composition, @id = a1, a2, a3, a4, a5 else @e, @id, @op, @mapping, @composition = a1, a2, a3, a4, a5 @op ||= op_block end v = Array.new(v, @e) if v.is_a?(Integer) @n = v.size @log = (@n - 1).bit_length @size = 1 << @log @d = Array.new(2 * @size, e) @lz = Array.new(@size, id) @n.times { |i| @d[@size + i] = v[i] } (@size - 1).downto(1) { |i| update(i) } end def set_mapping(&mapping) @mapping = mapping end def set_composition(&composition) @composition = composition end def set(pos, x) pos += @size @log.downto(1) { |i| push(pos >> i) } @d[pos] = x 1.upto(@log) { |i| update(pos >> i) } end alias []= set def get(pos) pos += @size @log.downto(1) { |i| push(pos >> i) } @d[pos] end alias [] get def prod(l, r = nil) if r.nil? # if 1st argument l is Range if r = l.end r += @n if r < 0 r += 1 unless l.exclude_end? else r = @n end l = l.begin l += @n if l < 0 end return @e if l == r l += @size r += @size @log.downto(1) do |i| push(l >> i) if (l >> i) << i != l push(r >> i) if (r >> i) << i != r end sml = @e smr = @e while l < r if l.odd? sml = @op.call(sml, @d[l]) l += 1 end if r.odd? r -= 1 smr = @op.call(@d[r], smr) end l >>= 1 r >>= 1 end @op.call(sml, smr) end def all_prod @d[1] end # apply(pos, f) # apply(l, r, f) -> range_apply(l, r, f) # apply(l...r, f) -> range_apply(l, r, f) ... [Experimental] def apply(pos, f, fr = nil) if fr return range_apply(pos, f, fr) elsif pos.is_a?(Range) l = pos.begin l += @n if l < 0 if r = pos.end r += @n if r < 0 r += 1 unless pos.exclude_end? else r = @n end return range_apply(l, r, f) end pos += @size @log.downto(1) { |i| push(pos >> i) } @d[pos] = @mapping.call(f, @d[pos]) 1.upto(@log) { |i| update(pos >> i) } end def range_apply(l, r, f) return if l == r l += @size r += @size @log.downto(1) do |i| push(l >> i) if (l >> i) << i != l push((r - 1) >> i) if (r >> i) << i != r end l2 = l r2 = r while l < r (all_apply(l, f); l += 1) if l.odd? (r -= 1; all_apply(r, f)) if r.odd? l >>= 1 r >>= 1 end l = l2 r = r2 1.upto(@log) do |i| update(l >> i) if (l >> i) << i != l update((r - 1) >> i) if (r >> i) << i != r end end def max_right(l, &g) return @n if l == @n l += @size @log.downto(1) { |i| push(l >> i) } sm = @e loop do l >>= 1 while l.even? unless g.call(@op.call(sm, @d[l])) while l < @size push(l) l <<= 1 if g.call(@op.call(sm, @d[l])) sm = @op.call(sm, @d[l]) l += 1 end end return l - @size end sm = @op.call(sm, @d[l]) l += 1 break if l & -l == l end @n end def min_left(r, &g) return 0 if r == 0 r += @size @log.downto(1) { |i| push((r - 1) >> i) } sm = @e loop do r -= 1 r /= 2 while r > 1 && r.odd? unless g.call(@op.call(@d[r], sm)) while r < @size push(r) r = r * 2 + 1 if g.call(@op.call(@d[r], sm)) sm = @op.call(@d[r], sm) r -= 1 end end return r + 1 - @size end sm = @op.call(@d[r], sm) break if (r & -r) == r end 0 end def update(k) @d[k] = @op.call(@d[2 * k], @d[2 * k + 1]) end def all_apply(k, f) @d[k] = @mapping.call(f, @d[k]) @lz[k] = @composition.call(f, @lz[k]) if k < @size end def push(k) all_apply(2 * k, @lz[k]) all_apply(2 * k + 1, @lz[k]) @lz[k] = @id end end LazySegTree = LazySegtree end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # usage : # # conv = Convolution.new(mod, [primitive_root]) # conv.convolution(a, b) #=> convolution a and b modulo mod. # class Convolution def initialize(mod = 998_244_353, primitive_root = nil) @mod = mod cnt2 = bsf(@mod - 1) e = (primitive_root || calc_primitive_root(mod)).pow((@mod - 1) >> cnt2, @mod) ie = e.pow(@mod - 2, @mod) es = [0] * (cnt2 - 1) ies = [0] * (cnt2 - 1) cnt2.downto(2){ |i| es[i - 2] = e ies[i - 2] = ie e = e * e % @mod ie = ie * ie % @mod } now = inow = 1 @sum_e = [0] * cnt2 @sum_ie = [0] * cnt2 (cnt2 - 1).times{ |i| @sum_e[i] = es[i] * now % @mod now = now * ies[i] % @mod @sum_ie[i] = ies[i] * inow % @mod inow = inow * es[i] % @mod } end def convolution(a, b) n = a.size m = b.size return [] if n == 0 || m == 0 h = (n + m - 2).bit_length raise ArgumentError if h > @sum_e.size z = 1 << h a = a + [0] * (z - n) b = b + [0] * (z - m) batterfly(a, h) batterfly(b, h) c = a.zip(b).map{ |a, b| a * b % @mod } batterfly_inv(c, h) iz = z.pow(@mod - 2, @mod) return c[0, n + m - 1].map{ |c| c * iz % @mod } end def batterfly(a, h) 1.upto(h){ |ph| w = 1 << (ph - 1) p = 1 << (h - ph) now = 1 w.times{ |s| offset = s << (h - ph + 1) offset.upto(offset + p - 1){ |i| l = a[i] r = a[i + p] * now % @mod a[i] = l + r a[i + p] = l - r } now = now * @sum_e[bsf(~s)] % @mod } } end def batterfly_inv(a, h) h.downto(1){ |ph| w = 1 << (ph - 1) p = 1 << (h - ph) inow = 1 w.times{ |s| offset = s << (h - ph + 1) offset.upto(offset + p - 1){ |i| l = a[i] r = a[i + p] a[i] = l + r a[i + p] = (l - r) * inow % @mod } inow = inow * @sum_ie[bsf(~s)] % @mod } } end def bsf(x) (x & -x).bit_length - 1 end def calc_primitive_root(mod) return 1 if mod == 2 return 3 if mod == 998_244_353 divs = [2] x = (mod - 1) / 2 x /= 2 while x.even? i = 3 while i * i <= x if x % i == 0 divs << i x /= i while x % i == 0 end i += 2 end divs << x if x > 1 g = 2 loop{ return g if divs.none?{ |d| g.pow((mod - 1) / d, mod) == 1 } g += 1 } end private :batterfly, :batterfly_inv, :bsf, :calc_primitive_root end # [EXPERIMENTAL] def convolution(a, b, mod: 998_244_353, k: 35, z: 99) n = a.size m = b.size return [] if n == 0 || m == 0 raise ArgumentError if a.min < 0 || b.min < 0 format = "%0#{k}x" # "%024x" sa = "" sb = "" a.each{ |x| sa << (format % x) } b.each{ |x| sb << (format % x) } zero = '0' s = zero * z + ("%x" % (sa.hex * sb.hex)) i = -(n + m - 1) * k - 1 Array.new(n + m - 1){ (s[i + 1..i += k] || zero).hex % mod } end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # Strongly Connected Components class SCC # initialize graph with n vertices def initialize(n) @n = n @edges = Array.new(n) { [] } end # add directed edge def add_edge(from, to) unless 0 <= from && from < @n && 0 <= to && to < @n msg = "Wrong params: from=#{from} and to=#{to} must be in 0...#{@n}" raise ArgumentError.new(msg) end @edges[from] << to self end def add_edges(edges) edges.each{ |from, to| add_edge(from, to) } self end def add(x, to = nil) to ? add_edge(x, to) : add_edges(x) end # returns list of strongly connected components # the components are sorted in topological order # O(@n + @edges.sum(&:size)) def scc group_num, ids = scc_ids groups = Array.new(group_num) { [] } ids.each_with_index { |id, i| groups[id] << i } groups end private def scc_ids now_ord = 0 visited = [] low = Array.new(@n, 1 << 60) ord = Array.new(@n, -1) group_num = 0 (0...@n).each do |v| next if ord[v] != -1 stack = [[v, 0]] while (v, i = stack.pop) if i == 0 visited << v low[v] = ord[v] = now_ord now_ord += 1 end while i < @edges[v].size u = @edges[v][i] i += 1 if ord[u] == -1 stack << [v, i] << [u, 0] break 1 end end and next low[v] = [low[v], @edges[v].map { |e| low[e] }.min || @n].min next if low[v] != ord[v] while (u = visited.pop) low[u] = @n ord[u] = group_num break if u == v end group_num += 1 end end ord.map! { |e| group_num - e - 1 } [group_num, ord] end end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb class Deque include Enumerable def self.[](*args) new(args) end def initialize(arg = [], value = nil, initial_capacity: 0) ary = arg ary = Array.new(arg, value) if arg.is_a?(Integer) @n = [initial_capacity, ary.size].max + 1 @buf = ary + [nil] * (@n - ary.size) @head = 0 @tail = ary.size @reverse_count = 0 end def empty? size == 0 end def size (@tail - @head) % @n end alias length size def <<(x) reversed? ? __unshift(x) : __push(x) end def push(*args) args.each{ |x| self << x } self end alias append push def unshift(*args) if reversed? args.reverse_each{ |e| __push(e) } else args.reverse_each{ |e| __unshift(e) } end self end alias prepend unshift def pop reversed? ? __shift : __pop end def shift reversed? ? __pop : __shift end def last self[-1] end def slice(idx) sz = size return nil if idx < -sz || sz <= idx @buf[__index(idx)] end def [](a, b = nil) if b slice2(a, b) elsif a.is_a?(Range) s = a.begin t = a.end t -= 1 if a.exclude_end? slice2(s, t - s + 1) else slice1(a) end end def at(idx) slice1(idx) end private def slice1(idx) sz = size return nil if idx < -sz || sz <= idx @buf[__index(idx)] end private def slice2(i, t) sz = size return nil if t < 0 || i > sz if i == sz Deque[] else j = [i + t - 1, sz].min slice_indexes(i, j) end end private def slice_indexes(i, j) i, j = j, i if reversed? s = __index(i) t = __index(j) + 1 Deque.new(__to_a(s, t)) end def []=(idx, value) @buf[__index(idx)] = value end def ==(other) return false unless size == other.size to_a == other.to_a end def hash to_a.hash end def reverse dup.reverse! end def reverse! @reverse_count += 1 self end def reversed? @reverse_count & 1 == 1 end def dig(*args) case args.size when 0 raise ArgumentError.new("wrong number of arguments (given 0, expected 1+)") when 1 self[args[0].to_int] else i = args.shift.to_int self[i]&.dig(*args) end end def each(&block) return enum_for(:each) unless block_given? if @head <= @tail if reversed? @buf[@head...@tail].reverse_each(&block) else @buf[@head...@tail].each(&block) end elsif reversed? @buf[0...@tail].reverse_each(&block) @buf[@head..-1].reverse_each(&block) else @buf[@head..-1].each(&block) @buf[0...@tail].each(&block) end end def clear @n = 1 @buf = [] @head = 0 @tail = 0 @reverse_count = 0 self end def join(sep = $OFS) to_a.join(sep) end def rotate!(cnt = 1) return self if cnt == 0 cnt %= size if cnt < 0 || size > cnt cnt.times{ push(shift) } self end def rotate(cnt = 1) return self if cnt == 0 cnt %= size if cnt < 0 || size > cnt ret = dup @buf = @buf.dup cnt.times{ ret.push(ret.shift) } ret end def sample return nil if empty? self[rand(size)] end def shuffle Deque.new(to_a.shuffle) end def replace(other) ary = other.to_a @n = ary.size + 1 @buf = ary + [nil] * (@n - ary.size) @head = 0 @tail = ary.size @reverse_count = 0 self end def swap(i, j) i = __index(i) j = __index(j) @buf[i], @buf[j] = @buf[j], @buf[i] self end def to_a __to_a end # alias to_ary to_a private def __to_a(s = @head, t = @tail) res = s <= t ? @buf[s...t] : @buf[s..-1].concat(@buf[0...t]) reversed? ? res.reverse : res end def to_s "#{self.class}#{to_a}" end def inspect "Deque#{to_a}" # "Deque#{to_a}(@n=#{@n}, @buf=#{@buf}, @head=#{@head}, @tail=#{@tail}, "\ # "size #{size}#{' full' if __full?}#{' rev' if reversed?})" end private def __push(x) __extend if __full? @buf[@tail] = x @tail += 1 @tail %= @n self end private def __unshift(x) __extend if __full? @buf[(@head - 1) % @n] = x @head -= 1 @head %= @n self end private def __pop return nil if empty? ret = @buf[(@tail - 1) % @n] @tail -= 1 @tail %= @n ret end private def __shift return nil if empty? ret = @buf[@head] @head += 1 @head %= @n ret end private def __full? size >= @n - 1 end private def __index(i) l = size raise IndexError, "index out of range: #{i}" unless -l <= i && i < l i = -(i + 1) if reversed? i += l if i < 0 (@head + i) % @n end private def __extend if @tail + 1 == @head tail = @buf.shift(@tail + 1) @buf.concat(tail).concat([nil] * @n) @head = 0 @tail = @n - 1 @n = @buf.size else @buf[(@tail + 1)..(@tail + 1)] = [nil] * @n @n = @buf.size @head += @n if @head > 0 end end end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # Use `Integer#pow` unless m == 1 def pow_mod(x, n, m) return 0 if m == 1 r, y = 1, x % m while n > 0 r = r * y % m if n.odd? y = y * y % m n >>= 1 end r end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # Priority Queue # Reference: https://github.com/python/cpython/blob/main/Lib/heapq.py class PriorityQueue # By default, the priority queue returns the maximum element first. # If a block is given, the priority between the elements is determined with it. # For example, the following block is given, the priority queue returns the minimum element first. # `PriorityQueue.new { |x, y| x < y }` # # A heap is an array for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k, counting elements from 0. def initialize(array = [], &comp) @heap = array @comp = comp || proc { |x, y| x > y } heapify end def self.max(array) new(array) end def self.min(array) new(array){ |x, y| x < y } end def self.[](*array, &comp) new(array, &comp) end attr_reader :heap alias to_a heap # Push new element to the heap. def push(item) shift_down(0, @heap.push(item).size - 1) self end alias << push alias append push # Pop the element with the highest priority. def pop latest = @heap.pop return latest if empty? ret_item = heap[0] heap[0] = latest shift_up(0) ret_item end # Get the element with the highest priority. def get @heap[0] end alias top get alias first get # Returns true if the heap is empty. def empty? @heap.empty? end def size @heap.size end def to_s "<#{self.class}: @heap:(#{heap.join(', ')}), @comp:<#{@comp.class} #{@comp.source_location.join(':')}>>" end private def heapify (@heap.size / 2 - 1).downto(0) { |i| shift_up(i) } end def shift_up(pos) end_pos = @heap.size start_pos = pos new_item = @heap[pos] left_child_pos = 2 * pos + 1 while left_child_pos < end_pos right_child_pos = left_child_pos + 1 if right_child_pos < end_pos && @comp.call(@heap[right_child_pos], @heap[left_child_pos]) left_child_pos = right_child_pos end # Move the higher priority child up. @heap[pos] = @heap[left_child_pos] pos = left_child_pos left_child_pos = 2 * pos + 1 end @heap[pos] = new_item shift_down(start_pos, pos) end def shift_down(star_pos, pos) new_item = @heap[pos] while pos > star_pos parent_pos = (pos - 1) >> 1 parent = @heap[parent_pos] break if @comp.call(parent, new_item) @heap[pos] = parent pos = parent_pos end @heap[pos] = new_item end end HeapQueue = PriorityQueue end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # lcp array for array of integers or string def lcp_array(s, sa) s = s.bytes if s.is_a?(String) n = s.size rnk = [0] * n sa.each_with_index{ |sa, id| rnk[sa] = id } lcp = [0] * (n - 1) h = 0 n.times{ |i| h -= 1 if h > 0 next if rnk[i] == 0 j = sa[rnk[i] - 1] h += 1 while j + h < n && i + h < n && s[j + h] == s[i + h] lcp[rnk[i] - 1] = h } return lcp end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # Use `x.pow(m - 2, m)` instead of `inv_mod(x, m)` if m is a prime number. def inv_mod(x, m) z = _inv_gcd(x, m) raise ArgumentError unless z.first == 1 z[1] end def _inv_gcd(a, b) a %= b # safe_mod s, t = b, a m0, m1 = 0, 1 while t > 0 u = s / t s -= t * u m0 -= m1 * u s, t = t, s m0, m1 = m1, m0 end m0 += b / s if m0 < 0 [s, m0] end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb require_relative './priority_queue.rb' # Min Cost Flow Grapsh class MinCostFlow def initialize(n) @n = n @pos = [] @g_to = Array.new(n) { [] } @g_rev = Array.new(n) { [] } @g_cap = Array.new(n) { [] } @g_cost = Array.new(n) { [] } @pv = Array.new(n) @pe = Array.new(n) @dual = Array.new(n, 0) end def add_edge(from, to, cap, cost) edge_number = @pos.size @pos << [from, @g_to[from].size] from_id = @g_to[from].size to_id = @g_to[to].size to_id += 1 if from == to @g_to[from] << to @g_rev[from] << to_id @g_cap[from] << cap @g_cost[from] << cost @g_to[to] << from @g_rev[to] << from_id @g_cap[to] << 0 @g_cost[to] << -cost edge_number end def add_edges(edges) edges.each{ |from, to, cap, cost| add_edge(from, to, cap, cost) } self end def add(x, to = nil, cap = nil, cost = nil) cost ? add_edge(x, to, cap, cost) : add_edges(x) end def get_edge(i) from, id = @pos[i] to = @g_to[from][id] rid = @g_rev[from][id] [from, to, @g_cap[from][id] + @g_cap[to][rid], @g_cap[to][rid], @g_cost[from][id]] end alias edge get_edge alias [] get_edge def edges @pos.map do |(from, id)| to = @g_to[from][id] rid = @g_rev[from][id] [from, to, @g_cap[from][id] + @g_cap[to][rid], @g_cap[to][rid], @g_cost[from][id]] end end def flow(s, t, flow_limit = Float::MAX) slope(s, t, flow_limit).last end alias min_cost_max_flow flow def dual_ref(s, t) dist = Array.new(@n, Float::MAX) @pv.fill(-1) @pe.fill(-1) vis = Array.new(@n, false) que = PriorityQueue.new { |par, chi| par[0] < chi[0] } dist[s] = 0 que.push([0, s]) while (v = que.pop) v = v[1] next if vis[v] vis[v] = true break if v == t @g_to[v].size.times do |i| to = @g_to[v][i] next if vis[to] || @g_cap[v][i] == 0 cost = @g_cost[v][i] - @dual[to] + @dual[v] next unless dist[to] - dist[v] > cost dist[to] = dist[v] + cost @pv[to] = v @pe[to] = i que.push([dist[to], to]) end end return false unless vis[t] @n.times do |i| next unless vis[i] @dual[i] -= dist[t] - dist[i] end true end def slope(s, t, flow_limit = Float::MAX) flow = 0 cost = 0 prev_cost_per_flow = -1 result = [[flow, cost]] while flow < flow_limit break unless dual_ref(s, t) c = flow_limit - flow v = t while v != s c = @g_cap[@pv[v]][@pe[v]] if c > @g_cap[@pv[v]][@pe[v]] v = @pv[v] end v = t while v != s nv = @pv[v] id = @pe[v] @g_cap[nv][id] -= c @g_cap[v][@g_rev[nv][id]] += c v = nv end d = -@dual[s] flow += c cost += c * d result.pop if prev_cost_per_flow == d result << [flow, cost] prev_cost_per_flow = d end result end alias min_cost_slop slope end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb require_relative './core_ext/modint.rb' # ModInt class ModInt < Numeric class << self def set_mod(mod) raise ArgumentError unless mod.is_a?(Integer) && (1 <= mod) $_mod = mod $_mod_is_prime = ModInt.prime?(mod) end def mod=(mod) set_mod mod end def mod $_mod end def raw(val) x = allocate x.val = val.to_i x end def prime?(n) return false if n <= 1 return true if (n == 2) || (n == 7) || (n == 61) return false if (n & 1) == 0 d = n - 1 d >>= 1 while (d & 1) == 0 [2, 7, 61].each do |a| t = d y = a.pow(t, n) while (t != n - 1) && (y != 1) && (y != n - 1) y = y * y % n t <<= 1 end return false if (y != n - 1) && ((t & 1) == 0) end true end def inv_gcd(a, b) a %= b return [b, 0] if a == 0 s, t = b, a m0, m1 = 0, 1 while t != 0 u = s / t s -= t * u m0 -= m1 * u s, t = t, s m0, m1 = m1, m0 end m0 += b / s if m0 < 0 [s, m0] end end attr_accessor :val alias to_i val def initialize(val = 0) @val = val.to_i % $_mod end def inc! @val += 1 @val = 0 if @val == $_mod self end def dec! @val = $_mod if @val == 0 @val -= 1 self end def add!(other) @val = (@val + other.to_i) % $_mod self end def sub!(other) @val = (@val - other.to_i) % $_mod self end def mul!(other) @val = @val * other.to_i % $_mod self end def div!(other) mul! inv_internal(other.to_i) end def +@ self end def -@ ModInt.raw($_mod - @val) end def **(other) $_mod == 1 ? 0 : ModInt.raw(@val.pow(other, $_mod)) end alias pow ** def inv ModInt.raw(inv_internal(@val) % $_mod) end def coerce(other) [ModInt(other), self] end def +(other) dup.add! other end def -(other) dup.sub! other end def *(other) dup.mul! other end def /(other) dup.div! other end def ==(other) @val == other.to_i end def pred dup.add!(-1) end def succ dup.add! 1 end def zero? @val == 0 end def dup ModInt.raw(@val) end def to_int @val end def to_s @val.to_s end def inspect "#{@val} mod #{$_mod}" end private def inv_internal(a) if $_mod_is_prime raise(RangeError, 'no inverse') if a == 0 a.pow($_mod - 2, $_mod) else g, x = ModInt.inv_gcd(a, $_mod) g == 1 ? x : raise(RangeError, 'no inverse') end end end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb def floor_sum(n, m, a, b) raise ArgumentError if n < 0 || m < 1 res = 0 if a < 0 a2 = a % m res -= n * (n - 1) / 2 * ((a2 - a) / m) a = a2 end if b < 0 b2 = b % m res -= n * ((b2 - b) / m) b = b2 end res + floor_sum_unsigned(n, m, a, b) end def floor_sum_unsigned(n, m, a, b) res = 0 while true if a >= m res += n * (n - 1) / 2 * (a / m) a %= m end if b >= m res += n * (b / m) b %= m end y_max = a * n + b break if y_max < m n = y_max / m b = y_max % m m, a = a, m end res end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # Segment Tree class Segtree attr_reader :d, :op, :n, :leaf_size, :log # new(v, e){ |x, y| } # new(v, op, e) def initialize(a0, a1, a2 = nil, &block) if a2.nil? @e, @op = a1, proc(&block) v = (a0.is_a?(Array) ? a0 : [@e] * a0) else @op, @e = a1, a2 v = (a0.is_a?(Array) ? a0 : [@e] * a0) end @n = v.size @log = (@n - 1).bit_length @leaf_size = 1 << @log @d = Array.new(@leaf_size * 2, @e) v.each_with_index { |v_i, i| @d[@leaf_size + i] = v_i } (@leaf_size - 1).downto(1) { |i| update(i) } end def set(q, x) q += @leaf_size @d[q] = x 1.upto(@log) { |i| update(q >> i) } end alias []= set def get(pos) @d[@leaf_size + pos] end alias [] get def prod(l, r = nil) if r.nil? # if 1st argument l is Range if r = l.end r += @n if r < 0 r += 1 unless l.exclude_end? else r = @n end l = l.begin l += @n if l < 0 end return @e if l == r sml = @e smr = @e l += @leaf_size r += @leaf_size while l < r if l[0] == 1 sml = @op.call(sml, @d[l]) l += 1 end if r[0] == 1 r -= 1 smr = @op.call(@d[r], smr) end l /= 2 r /= 2 end @op.call(sml, smr) end def all_prod @d[1] end def max_right(l, &block) return @n if l == @n f = proc(&block) l += @leaf_size sm = @e loop do l /= 2 while l.even? unless f.call(@op.call(sm, @d[l])) while l < @leaf_size l *= 2 if f.call(@op.call(sm, @d[l])) sm = @op.call(sm, @d[l]) l += 1 end end return l - @leaf_size end sm = @op.call(sm, @d[l]) l += 1 break if (l & -l) == l end @n end def min_left(r, &block) return 0 if r == 0 f = proc(&block) r += @leaf_size sm = @e loop do r -= 1 r /= 2 while r > 1 && r.odd? unless f.call(@op.call(@d[r], sm)) while r < @leaf_size r = r * 2 + 1 if f.call(@op.call(@d[r], sm)) sm = @op.call(@d[r], sm) r -= 1 end end return r + 1 - @leaf_size end sm = @op.call(@d[r], sm) break if (r & -r) == r end 0 end def update(k) @d[k] = @op.call(@d[2 * k], @d[2 * k + 1]) end # def inspect # for debug # t = 0 # res = "Segtree @e = #{@e}, @n = #{@n}, @leaf_size = #{@leaf_size} @op = #{@op}\n " # a = @d[1, @d.size - 1] # a.each_with_index do |e, i| # res << e.to_s << ' ' # if t == i && i < @leaf_size # res << "\n " # t = t * 2 + 2 # end # end # res # end end SegTree = Segtree end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # MaxFlowGraph class MaxFlow def initialize(n) @n = n @pos = [] @g = Array.new(n) { [] } end def add_edge(from, to, cap) edge_number = @pos.size @pos << [from, @g[from].size] from_id = @g[from].size to_id = @g[to].size to_id += 1 if from == to @g[from] << [to, to_id, cap] @g[to] << [from, from_id, 0] edge_number end def add_edges(edges) edges.each{ |from, to, cap| add_edge(from, to, cap) } self end def add(x, to = nil, cap = nil) cap ? add_edge(x, to, cap) : add_edges(x) end def push(edge) add_edge(*edge) end alias << push # return edge = [from, to, cap, flow] def [](i) from, from_id = @pos[i] to, to_id, cap = @g[from][from_id] # edge _from, _from_id, flow = @g[to][to_id] # reverse edge [from, to, cap + flow, flow] end alias get_edge [] alias edge [] def edges @pos.map do |(from, from_id)| to, to_id, cap = @g[from][from_id] _from, _from_id, flow = @g[to][to_id] [from, to, cap + flow, flow] end end def change_edge(i, new_cap, new_flow) from, from_id = @pos[i] e = @g[from][from_id] re = @g[e[0]][e[1]] e[2] = new_cap - new_flow re[2] = new_flow end def flow(s, t, flow_limit = 1 << 64) flow = 0 while flow < flow_limit level = bfs(s, t) break if level[t] == -1 iter = [0] * @n while flow < flow_limit f = dfs(t, flow_limit - flow, s, level, iter) break if f == 0 flow += f end end flow end alias max_flow flow def min_cut(s) visited = Array.new(@n, false) que = [s] while (q = que.shift) visited[q] = true @g[q].each do |(to, _rev, cap)| if cap > 0 && !visited[to] visited[to] = true que << to end end end visited end private def bfs(s, t) level = Array.new(@n, -1) level[s] = 0 que = [s] while (v = que.shift) @g[v].each do |u, _, cap| next if cap == 0 || level[u] >= 0 level[u] = level[v] + 1 return level if u == t que << u end end level end def dfs(v, up, s, level, iter) return up if v == s res = 0 level_v = level[v] while iter[v] < @g[v].size i = iter[v] e = @g[v][i] cap = @g[e[0]][e[1]][2] if level_v > level[e[0]] && cap > 0 d = dfs(e[0], (up - res < cap ? up - res : cap), s, level, iter) if d > 0 @g[v][i][2] += d @g[e[0]][e[1]][2] -= d res += d break if res == up end end iter[v] += 1 end res end end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # Disjoint Set Union class DSU def initialize(n = 0) @n = n @parent_or_size = Array.new(n, -1) # root node: -1 * component size # otherwise: parent end attr_reader :parent_or_size, :n def merge(a, b) x = leader(a) y = leader(b) return x if x == y x, y = y, x if -@parent_or_size[x] < -@parent_or_size[y] @parent_or_size[x] += @parent_or_size[y] @parent_or_size[y] = x end alias unite merge def same?(a, b) leader(a) == leader(b) end alias same same? def leader(a) unless 0 <= a && a < @n raise ArgumentError.new, "#{a} is out of range (0...#{@n})" end @parent_or_size[a] < 0 ? a : (@parent_or_size[a] = leader(@parent_or_size[a])) end alias root leader alias find leader def [](a) if @n <= a @parent_or_size.concat([-1] * (a - @n + 1)) @n = @parent_or_size.size end @parent_or_size[a] < 0 ? a : (@parent_or_size[a] = self[@parent_or_size[a]]) end def size(a) -@parent_or_size[leader(a)] end def groups (0 ... @parent_or_size.size).group_by{ |i| leader(i) }.values end def to_s "<#{self.class}: @n=#{@n}, #{@parent_or_size}>" end end UnionFind = DSU end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # induce sort (internal method) def sa_is_induce(s, ls, sum_l, sum_s, lms) n = s.size sa = [-1] * n buf = sum_s.dup lms.each{ |lms| if lms != n sa[buf[s[lms]]] = lms buf[s[lms]] += 1 end } buf = sum_l.dup sa[buf[s[-1]]] = n - 1 buf[s[-1]] += 1 sa.each{ |v| if v >= 1 && !ls[v - 1] sa[buf[s[v - 1]]] = v - 1 buf[s[v - 1]] += 1 end } buf = sum_l.dup sa.reverse_each{ |v| if v >= 1 && ls[v - 1] buf[s[v - 1] + 1] -= 1 sa[buf[s[v - 1] + 1]] = v - 1 end } return sa end # SA-IS (internal method) def sa_is(s, upper) n = s.size return [] if n == 0 return [0] if n == 1 ls = [false] * n (n - 2).downto(0){ |i| ls[i] = (s[i] == s[i + 1] ? ls[i + 1] : s[i] < s[i + 1]) } sum_l = [0] * (upper + 1) sum_s = [0] * (upper + 1) n.times{ |i| if ls[i] sum_l[s[i] + 1] += 1 else sum_s[s[i]] += 1 end } 0.upto(upper){ |i| sum_s[i] += sum_l[i] sum_l[i + 1] += sum_s[i] if i < upper } lms = (1 ... n).select{ |i| !ls[i - 1] && ls[i] } m = lms.size lms_map = [-1] * (n + 1) lms.each_with_index{ |lms, id| lms_map[lms] = id } sa = sa_is_induce(s, ls, sum_l, sum_s, lms) return sa if m == 0 sorted_lms = sa.select{ |sa| lms_map[sa] != -1 } rec_s = [0] * m rec_upper = 0 rec_s[lms_map[sorted_lms[0]]] = 0 1.upto(m - 1) do |i| l, r = sorted_lms[i - 1, 2] end_l = lms[lms_map[l] + 1] || n end_r = lms[lms_map[r] + 1] || n same = true if end_l - l == end_r - r while l < end_l break if s[l] != s[r] l += 1 r += 1 end same = false if l == n || s[l] != s[r] else same = false end rec_upper += 1 if not same rec_s[lms_map[sorted_lms[i]]] = rec_upper end sa_is(rec_s, rec_upper).each_with_index{ |rec_sa, id| sorted_lms[id] = lms[rec_sa] } return sa_is_induce(s, ls, sum_l, sum_s, sorted_lms) end # suffix array for array of integers or string def suffix_array(s, upper = nil) if upper s.each{ |s| raise ArgumentError if s < 0 || upper < s } else case s when Array # compression n = s.size idx = (0 ... n).sort_by{ |i| s[i] } t = [0] * n upper = 0 t[idx[0]] = 0 1.upto(n - 1){ |i| upper += 1 if s[idx[i - 1]] != s[idx[i]] t[idx[i]] = upper } s = t when String upper = 255 s = s.bytes end end return sa_is(s, upper) end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # this implementation is different from ACL because of calculation time # ref : https://snuke.hatenablog.com/entry/2014/12/03/214243 # ACL implementation : https://atcoder.jp/contests/abc135/submissions/18836384 (731ms) # this implementation : https://atcoder.jp/contests/abc135/submissions/18836378 (525ms) def z_algorithm(s) n = s.size return [] if n == 0 s = s.codepoints if s.is_a?(String) z = [0] * n z[0] = n i, j = 1, 0 while i < n j += 1 while i + j < n && s[j] == s[i + j] z[i] = j if j == 0 i += 1 next end k = 1 while i + k < n && k + z[k] < j z[i + k] = z[k] k += 1 end i += k j -= k end return z end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb # return [rem, mod] or [0, 0] (if no solution) def crt(r, m) unless r.size == m.size raise ArgumentError.new("size of r and m must be equal for crt(r, m)") end n = r.size r0, m0 = 0, 1 n.times do |i| raise ArgumentError if m[i] < 1 r1, m1 = r[i] % m[i], m[i] if m0 < m1 r0, r1 = r1, r0 m0, m1 = m1, m0 end if m0 % m1 == 0 return [0, 0] if r0 % m1 != r1 next end g, im = inv_gcd(m0, m1) u1 = m1 / g return [0, 0] if (r1 - r0) % g != 0 x = (r1 - r0) / g * im % u1 r0 += x * m0 m0 *= u1 r0 += m0 if r0 < 0 end return [r0, m0] end # internal method # return [g, x] s.t. g = gcd(a, b), x*a = g (mod b), 0 <= x < b/g def inv_gcd(a, b) a %= b return [b, 0] if a == 0 s, t = b, a m0, m1 = 0, 1 while t > 0 u, s = s.divmod(t) m0 -= m1 * u s, t = t, s m0, m1 = m1, m0 end m0 += b / s if m0 < 0 return [s, m0] end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb require_relative './scc.rb' # TwoSAT # Reference: https://github.com/atcoder/ac-library/blob/master/atcoder/twosat.hpp class TwoSAT def initialize(n) @n = n @answer = Array.new(n) @scc = SCC.new(2 * n) end attr_reader :answer def add_clause(i, f, j, g) unless 0 <= i && i < @n && 0 <= j && j < @n raise ArgumentError.new("i:#{i} and j:#{j} must be in (0...#{@n})") end @scc.add_edge(2 * i + (f ? 0 : 1), 2 * j + (g ? 1 : 0)) @scc.add_edge(2 * j + (g ? 0 : 1), 2 * i + (f ? 1 : 0)) nil end def satisfiable? id = @scc.send(:scc_ids)[1] @n.times do |i| return false if id[2 * i] == id[2 * i + 1] @answer[i] = id[2 * i] < id[2 * i + 1] end true end alias satisfiable satisfiable? end TwoSat = TwoSAT end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
def ModInt(val) AcLibraryRb::ModInt.new(val) end # Integer class Integer def to_modint AcLibraryRb::ModInt.new(self) end alias to_m to_modint end # String class String def to_modint AcLibraryRb::ModInt.new(to_i) end alias to_m to_modint end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
class Array def to_fenwick_tree AcLibraryRb::FenwickTree.new(self) end alias to_fetree to_fenwick_tree def to_priority_queue AcLibraryRb::PriorityQueue.new(self) end alias to_pq to_priority_queue end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
require "prime" class Integer # Returns the positive divisors of +self+ if +self+ is positive. # # == Example # 6.divisors #=> [1, 2, 3, 6] # 7.divisors #=> [1, 7] # 8.divisors #=> [1, 2, 4, 8] def divisors if prime? [1, self] elsif self == 1 [1] else xs = prime_division.map{ |p, n| Array.new(n + 1){ |e| p**e } } x = xs.pop x.product(*xs).map{ |t| t.inject(:*) }.sort end end # Iterates the given block for each divisor of +self+. # # == Example # ds = [] # 10.divisors{ |d| ds << d } # ds #=> [1, 2, 5, 10] def each_divisor(&block) block_given? ? divisors.each(&block) : enum_for(:each_divisor) end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Fenwick Tree class FenwickTree attr_reader :data, :size def initialize(arg) case arg when Array @size = arg.size @data = [0].concat(arg) (1 ... @size).each do |i| up = i + (i & -i) next if up > @size @data[up] += @data[i] end when Integer @size = arg @data = Array.new(@size + 1, 0) else raise ArgumentError.new("wrong argument. type is Array or Integer") end end def add(i, x) i += 1 while i <= @size @data[i] += x i += (i & -i) end end # .sum(l, r) # [l, r) <- Original # .sum(r) # [0, r) <- [Experimental] # .sum(l..r) # [l, r] <- [Experimental] def sum(a, b = nil) if b _sum(b) - _sum(a) elsif a.is_a?(Range) l = a.begin l += @size if l < 0 if r = a.end r += @size if r < 0 r += 1 unless a.exclude_end? else r = @size end _sum(r) - _sum(l) else _sum(a) end end def _sum(i) res = 0 while i > 0 res += @data[i] i &= i - 1 end res end alias left_sum _sum def to_s "<#{self.class}: @size=#{@size}, (#{@data[1..].join(', ')})>" end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Segment tree with Lazy propagation class LazySegtree attr_reader :d, :lz, :e, :id attr_accessor :op, :mapping, :composition # new(v, op, e, mapping, composition, id) # new(v, e, id, op, mapping, composition) # new(v, e, id){ |x, y| } def initialize(v, a1, a2, a3 = nil, a4 = nil, a5 = nil, &op_block) if a1.is_a?(Proc) @op, @e, @mapping, @composition, @id = a1, a2, a3, a4, a5 else @e, @id, @op, @mapping, @composition = a1, a2, a3, a4, a5 @op ||= op_block end v = Array.new(v, @e) if v.is_a?(Integer) @n = v.size @log = (@n - 1).bit_length @size = 1 << @log @d = Array.new(2 * @size, e) @lz = Array.new(@size, id) @n.times { |i| @d[@size + i] = v[i] } (@size - 1).downto(1) { |i| update(i) } end def set_mapping(&mapping) @mapping = mapping end def set_composition(&composition) @composition = composition end def set(pos, x) pos += @size @log.downto(1) { |i| push(pos >> i) } @d[pos] = x 1.upto(@log) { |i| update(pos >> i) } end alias []= set def get(pos) pos += @size @log.downto(1) { |i| push(pos >> i) } @d[pos] end alias [] get def prod(l, r = nil) if r.nil? # if 1st argument l is Range if r = l.end r += @n if r < 0 r += 1 unless l.exclude_end? else r = @n end l = l.begin l += @n if l < 0 end return @e if l == r l += @size r += @size @log.downto(1) do |i| push(l >> i) if (l >> i) << i != l push(r >> i) if (r >> i) << i != r end sml = @e smr = @e while l < r if l.odd? sml = @op.call(sml, @d[l]) l += 1 end if r.odd? r -= 1 smr = @op.call(@d[r], smr) end l >>= 1 r >>= 1 end @op.call(sml, smr) end def all_prod @d[1] end # apply(pos, f) # apply(l, r, f) -> range_apply(l, r, f) # apply(l...r, f) -> range_apply(l, r, f) ... [Experimental] def apply(pos, f, fr = nil) if fr return range_apply(pos, f, fr) elsif pos.is_a?(Range) l = pos.begin l += @n if l < 0 if r = pos.end r += @n if r < 0 r += 1 unless pos.exclude_end? else r = @n end return range_apply(l, r, f) end pos += @size @log.downto(1) { |i| push(pos >> i) } @d[pos] = @mapping.call(f, @d[pos]) 1.upto(@log) { |i| update(pos >> i) } end def range_apply(l, r, f) return if l == r l += @size r += @size @log.downto(1) do |i| push(l >> i) if (l >> i) << i != l push((r - 1) >> i) if (r >> i) << i != r end l2 = l r2 = r while l < r (all_apply(l, f); l += 1) if l.odd? (r -= 1; all_apply(r, f)) if r.odd? l >>= 1 r >>= 1 end l = l2 r = r2 1.upto(@log) do |i| update(l >> i) if (l >> i) << i != l update((r - 1) >> i) if (r >> i) << i != r end end def max_right(l, &g) return @n if l == @n l += @size @log.downto(1) { |i| push(l >> i) } sm = @e loop do l >>= 1 while l.even? unless g.call(@op.call(sm, @d[l])) while l < @size push(l) l <<= 1 if g.call(@op.call(sm, @d[l])) sm = @op.call(sm, @d[l]) l += 1 end end return l - @size end sm = @op.call(sm, @d[l]) l += 1 break if l & -l == l end @n end def min_left(r, &g) return 0 if r == 0 r += @size @log.downto(1) { |i| push((r - 1) >> i) } sm = @e loop do r -= 1 r /= 2 while r > 1 && r.odd? unless g.call(@op.call(@d[r], sm)) while r < @size push(r) r = r * 2 + 1 if g.call(@op.call(@d[r], sm)) sm = @op.call(@d[r], sm) r -= 1 end end return r + 1 - @size end sm = @op.call(@d[r], sm) break if (r & -r) == r end 0 end def update(k) @d[k] = @op.call(@d[2 * k], @d[2 * k + 1]) end def all_apply(k, f) @d[k] = @mapping.call(f, @d[k]) @lz[k] = @composition.call(f, @lz[k]) if k < @size end def push(k) all_apply(2 * k, @lz[k]) all_apply(2 * k + 1, @lz[k]) @lz[k] = @id end end LazySegTree = LazySegtree
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# usage : # # conv = Convolution.new(mod, [primitive_root]) # conv.convolution(a, b) #=> convolution a and b modulo mod. # class Convolution def initialize(mod = 998_244_353, primitive_root = nil) @mod = mod cnt2 = bsf(@mod - 1) e = (primitive_root || calc_primitive_root(mod)).pow((@mod - 1) >> cnt2, @mod) ie = e.pow(@mod - 2, @mod) es = [0] * (cnt2 - 1) ies = [0] * (cnt2 - 1) cnt2.downto(2){ |i| es[i - 2] = e ies[i - 2] = ie e = e * e % @mod ie = ie * ie % @mod } now = inow = 1 @sum_e = [0] * cnt2 @sum_ie = [0] * cnt2 (cnt2 - 1).times{ |i| @sum_e[i] = es[i] * now % @mod now = now * ies[i] % @mod @sum_ie[i] = ies[i] * inow % @mod inow = inow * es[i] % @mod } end def convolution(a, b) n = a.size m = b.size return [] if n == 0 || m == 0 h = (n + m - 2).bit_length raise ArgumentError if h > @sum_e.size z = 1 << h a = a + [0] * (z - n) b = b + [0] * (z - m) batterfly(a, h) batterfly(b, h) c = a.zip(b).map{ |a, b| a * b % @mod } batterfly_inv(c, h) iz = z.pow(@mod - 2, @mod) return c[0, n + m - 1].map{ |c| c * iz % @mod } end def batterfly(a, h) 1.upto(h){ |ph| w = 1 << (ph - 1) p = 1 << (h - ph) now = 1 w.times{ |s| offset = s << (h - ph + 1) offset.upto(offset + p - 1){ |i| l = a[i] r = a[i + p] * now % @mod a[i] = l + r a[i + p] = l - r } now = now * @sum_e[bsf(~s)] % @mod } } end def batterfly_inv(a, h) h.downto(1){ |ph| w = 1 << (ph - 1) p = 1 << (h - ph) inow = 1 w.times{ |s| offset = s << (h - ph + 1) offset.upto(offset + p - 1){ |i| l = a[i] r = a[i + p] a[i] = l + r a[i + p] = (l - r) * inow % @mod } inow = inow * @sum_ie[bsf(~s)] % @mod } } end def bsf(x) (x & -x).bit_length - 1 end def calc_primitive_root(mod) return 1 if mod == 2 return 3 if mod == 998_244_353 divs = [2] x = (mod - 1) / 2 x /= 2 while x.even? i = 3 while i * i <= x if x % i == 0 divs << i x /= i while x % i == 0 end i += 2 end divs << x if x > 1 g = 2 loop{ return g if divs.none?{ |d| g.pow((mod - 1) / d, mod) == 1 } g += 1 } end private :batterfly, :batterfly_inv, :bsf, :calc_primitive_root end # [EXPERIMENTAL] def convolution(a, b, mod: 998_244_353, k: 35, z: 99) n = a.size m = b.size return [] if n == 0 || m == 0 raise ArgumentError if a.min < 0 || b.min < 0 format = "%0#{k}x" # "%024x" sa = "" sb = "" a.each{ |x| sa << (format % x) } b.each{ |x| sb << (format % x) } zero = '0' s = zero * z + ("%x" % (sa.hex * sb.hex)) i = -(n + m - 1) * k - 1 Array.new(n + m - 1){ (s[i + 1..i += k] || zero).hex % mod } end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Strongly Connected Components class SCC # initialize graph with n vertices def initialize(n) @n = n @edges = Array.new(n) { [] } end # add directed edge def add_edge(from, to) unless 0 <= from && from < @n && 0 <= to && to < @n msg = "Wrong params: from=#{from} and to=#{to} must be in 0...#{@n}" raise ArgumentError.new(msg) end @edges[from] << to self end def add_edges(edges) edges.each{ |from, to| add_edge(from, to) } self end def add(x, to = nil) to ? add_edge(x, to) : add_edges(x) end # returns list of strongly connected components # the components are sorted in topological order # O(@n + @edges.sum(&:size)) def scc group_num, ids = scc_ids groups = Array.new(group_num) { [] } ids.each_with_index { |id, i| groups[id] << i } groups end private def scc_ids now_ord = 0 visited = [] low = Array.new(@n, 1 << 60) ord = Array.new(@n, -1) group_num = 0 (0...@n).each do |v| next if ord[v] != -1 stack = [[v, 0]] while (v, i = stack.pop) if i == 0 visited << v low[v] = ord[v] = now_ord now_ord += 1 end while i < @edges[v].size u = @edges[v][i] i += 1 if ord[u] == -1 stack << [v, i] << [u, 0] break 1 end end and next low[v] = [low[v], @edges[v].map { |e| low[e] }.min || @n].min next if low[v] != ord[v] while (u = visited.pop) low[u] = @n ord[u] = group_num break if u == v end group_num += 1 end end ord.map! { |e| group_num - e - 1 } [group_num, ord] end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
class Deque include Enumerable def self.[](*args) new(args) end def initialize(arg = [], value = nil, initial_capacity: 0) ary = arg ary = Array.new(arg, value) if arg.is_a?(Integer) @n = [initial_capacity, ary.size].max + 1 @buf = ary + [nil] * (@n - ary.size) @head = 0 @tail = ary.size @reverse_count = 0 end def empty? size == 0 end def size (@tail - @head) % @n end alias length size def <<(x) reversed? ? __unshift(x) : __push(x) end def push(*args) args.each{ |x| self << x } self end alias append push def unshift(*args) if reversed? args.reverse_each{ |e| __push(e) } else args.reverse_each{ |e| __unshift(e) } end self end alias prepend unshift def pop reversed? ? __shift : __pop end def shift reversed? ? __pop : __shift end def last self[-1] end def slice(idx) sz = size return nil if idx < -sz || sz <= idx @buf[__index(idx)] end def [](a, b = nil) if b slice2(a, b) elsif a.is_a?(Range) s = a.begin t = a.end t -= 1 if a.exclude_end? slice2(s, t - s + 1) else slice1(a) end end def at(idx) slice1(idx) end private def slice1(idx) sz = size return nil if idx < -sz || sz <= idx @buf[__index(idx)] end private def slice2(i, t) sz = size return nil if t < 0 || i > sz if i == sz Deque[] else j = [i + t - 1, sz].min slice_indexes(i, j) end end private def slice_indexes(i, j) i, j = j, i if reversed? s = __index(i) t = __index(j) + 1 Deque.new(__to_a(s, t)) end def []=(idx, value) @buf[__index(idx)] = value end def ==(other) return false unless size == other.size to_a == other.to_a end def hash to_a.hash end def reverse dup.reverse! end def reverse! @reverse_count += 1 self end def reversed? @reverse_count & 1 == 1 end def dig(*args) case args.size when 0 raise ArgumentError.new("wrong number of arguments (given 0, expected 1+)") when 1 self[args[0].to_int] else i = args.shift.to_int self[i]&.dig(*args) end end def each(&block) return enum_for(:each) unless block_given? if @head <= @tail if reversed? @buf[@head...@tail].reverse_each(&block) else @buf[@head...@tail].each(&block) end elsif reversed? @buf[0...@tail].reverse_each(&block) @buf[@head..-1].reverse_each(&block) else @buf[@head..-1].each(&block) @buf[0...@tail].each(&block) end end def clear @n = 1 @buf = [] @head = 0 @tail = 0 @reverse_count = 0 self end def join(sep = $OFS) to_a.join(sep) end def rotate!(cnt = 1) return self if cnt == 0 cnt %= size if cnt < 0 || size > cnt cnt.times{ push(shift) } self end def rotate(cnt = 1) return self if cnt == 0 cnt %= size if cnt < 0 || size > cnt ret = dup @buf = @buf.dup cnt.times{ ret.push(ret.shift) } ret end def sample return nil if empty? self[rand(size)] end def shuffle Deque.new(to_a.shuffle) end def replace(other) ary = other.to_a @n = ary.size + 1 @buf = ary + [nil] * (@n - ary.size) @head = 0 @tail = ary.size @reverse_count = 0 self end def swap(i, j) i = __index(i) j = __index(j) @buf[i], @buf[j] = @buf[j], @buf[i] self end def to_a __to_a end # alias to_ary to_a private def __to_a(s = @head, t = @tail) res = s <= t ? @buf[s...t] : @buf[s..-1].concat(@buf[0...t]) reversed? ? res.reverse : res end def to_s "#{self.class}#{to_a}" end def inspect "Deque#{to_a}" # "Deque#{to_a}(@n=#{@n}, @buf=#{@buf}, @head=#{@head}, @tail=#{@tail}, "\ # "size #{size}#{' full' if __full?}#{' rev' if reversed?})" end private def __push(x) __extend if __full? @buf[@tail] = x @tail += 1 @tail %= @n self end private def __unshift(x) __extend if __full? @buf[(@head - 1) % @n] = x @head -= 1 @head %= @n self end private def __pop return nil if empty? ret = @buf[(@tail - 1) % @n] @tail -= 1 @tail %= @n ret end private def __shift return nil if empty? ret = @buf[@head] @head += 1 @head %= @n ret end private def __full? size >= @n - 1 end private def __index(i) l = size raise IndexError, "index out of range: #{i}" unless -l <= i && i < l i = -(i + 1) if reversed? i += l if i < 0 (@head + i) % @n end private def __extend if @tail + 1 == @head tail = @buf.shift(@tail + 1) @buf.concat(tail).concat([nil] * @n) @head = 0 @tail = @n - 1 @n = @buf.size else @buf[(@tail + 1)..(@tail + 1)] = [nil] * @n @n = @buf.size @head += @n if @head > 0 end end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Use `Integer#pow` unless m == 1 def pow_mod(x, n, m) return 0 if m == 1 r, y = 1, x % m while n > 0 r = r * y % m if n.odd? y = y * y % m n >>= 1 end r end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Priority Queue # Reference: https://github.com/python/cpython/blob/main/Lib/heapq.py class PriorityQueue # By default, the priority queue returns the maximum element first. # If a block is given, the priority between the elements is determined with it. # For example, the following block is given, the priority queue returns the minimum element first. # `PriorityQueue.new { |x, y| x < y }` # # A heap is an array for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k, counting elements from 0. def initialize(array = [], &comp) @heap = array @comp = comp || proc { |x, y| x > y } heapify end def self.max(array) new(array) end def self.min(array) new(array){ |x, y| x < y } end def self.[](*array, &comp) new(array, &comp) end attr_reader :heap alias to_a heap # Push new element to the heap. def push(item) shift_down(0, @heap.push(item).size - 1) self end alias << push alias append push # Pop the element with the highest priority. def pop latest = @heap.pop return latest if empty? ret_item = heap[0] heap[0] = latest shift_up(0) ret_item end # Get the element with the highest priority. def get @heap[0] end alias top get alias first get # Returns true if the heap is empty. def empty? @heap.empty? end def size @heap.size end def to_s "<#{self.class}: @heap:(#{heap.join(', ')}), @comp:<#{@comp.class} #{@comp.source_location.join(':')}>>" end private def heapify (@heap.size / 2 - 1).downto(0) { |i| shift_up(i) } end def shift_up(pos) end_pos = @heap.size start_pos = pos new_item = @heap[pos] left_child_pos = 2 * pos + 1 while left_child_pos < end_pos right_child_pos = left_child_pos + 1 if right_child_pos < end_pos && @comp.call(@heap[right_child_pos], @heap[left_child_pos]) left_child_pos = right_child_pos end # Move the higher priority child up. @heap[pos] = @heap[left_child_pos] pos = left_child_pos left_child_pos = 2 * pos + 1 end @heap[pos] = new_item shift_down(start_pos, pos) end def shift_down(star_pos, pos) new_item = @heap[pos] while pos > star_pos parent_pos = (pos - 1) >> 1 parent = @heap[parent_pos] break if @comp.call(parent, new_item) @heap[pos] = parent pos = parent_pos end @heap[pos] = new_item end end HeapQueue = PriorityQueue
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# lcp array for array of integers or string def lcp_array(s, sa) s = s.bytes if s.is_a?(String) n = s.size rnk = [0] * n sa.each_with_index{ |sa, id| rnk[sa] = id } lcp = [0] * (n - 1) h = 0 n.times{ |i| h -= 1 if h > 0 next if rnk[i] == 0 j = sa[rnk[i] - 1] h += 1 while j + h < n && i + h < n && s[j + h] == s[i + h] lcp[rnk[i] - 1] = h } return lcp end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Use `x.pow(m - 2, m)` instead of `inv_mod(x, m)` if m is a prime number. def inv_mod(x, m) z = _inv_gcd(x, m) raise ArgumentError unless z.first == 1 z[1] end def _inv_gcd(a, b) a %= b # safe_mod s, t = b, a m0, m1 = 0, 1 while t > 0 u = s / t s -= t * u m0 -= m1 * u s, t = t, s m0, m1 = m1, m0 end m0 += b / s if m0 < 0 [s, m0] end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
require_relative './priority_queue.rb' # Min Cost Flow Grapsh class MinCostFlow def initialize(n) @n = n @pos = [] @g_to = Array.new(n) { [] } @g_rev = Array.new(n) { [] } @g_cap = Array.new(n) { [] } @g_cost = Array.new(n) { [] } @pv = Array.new(n) @pe = Array.new(n) @dual = Array.new(n, 0) end def add_edge(from, to, cap, cost) edge_number = @pos.size @pos << [from, @g_to[from].size] from_id = @g_to[from].size to_id = @g_to[to].size to_id += 1 if from == to @g_to[from] << to @g_rev[from] << to_id @g_cap[from] << cap @g_cost[from] << cost @g_to[to] << from @g_rev[to] << from_id @g_cap[to] << 0 @g_cost[to] << -cost edge_number end def add_edges(edges) edges.each{ |from, to, cap, cost| add_edge(from, to, cap, cost) } self end def add(x, to = nil, cap = nil, cost = nil) cost ? add_edge(x, to, cap, cost) : add_edges(x) end def get_edge(i) from, id = @pos[i] to = @g_to[from][id] rid = @g_rev[from][id] [from, to, @g_cap[from][id] + @g_cap[to][rid], @g_cap[to][rid], @g_cost[from][id]] end alias edge get_edge alias [] get_edge def edges @pos.map do |(from, id)| to = @g_to[from][id] rid = @g_rev[from][id] [from, to, @g_cap[from][id] + @g_cap[to][rid], @g_cap[to][rid], @g_cost[from][id]] end end def flow(s, t, flow_limit = Float::MAX) slope(s, t, flow_limit).last end alias min_cost_max_flow flow def dual_ref(s, t) dist = Array.new(@n, Float::MAX) @pv.fill(-1) @pe.fill(-1) vis = Array.new(@n, false) que = PriorityQueue.new { |par, chi| par[0] < chi[0] } dist[s] = 0 que.push([0, s]) while (v = que.pop) v = v[1] next if vis[v] vis[v] = true break if v == t @g_to[v].size.times do |i| to = @g_to[v][i] next if vis[to] || @g_cap[v][i] == 0 cost = @g_cost[v][i] - @dual[to] + @dual[v] next unless dist[to] - dist[v] > cost dist[to] = dist[v] + cost @pv[to] = v @pe[to] = i que.push([dist[to], to]) end end return false unless vis[t] @n.times do |i| next unless vis[i] @dual[i] -= dist[t] - dist[i] end true end def slope(s, t, flow_limit = Float::MAX) flow = 0 cost = 0 prev_cost_per_flow = -1 result = [[flow, cost]] while flow < flow_limit break unless dual_ref(s, t) c = flow_limit - flow v = t while v != s c = @g_cap[@pv[v]][@pe[v]] if c > @g_cap[@pv[v]][@pe[v]] v = @pv[v] end v = t while v != s nv = @pv[v] id = @pe[v] @g_cap[nv][id] -= c @g_cap[v][@g_rev[nv][id]] += c v = nv end d = -@dual[s] flow += c cost += c * d result.pop if prev_cost_per_flow == d result << [flow, cost] prev_cost_per_flow = d end result end alias min_cost_slop slope end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
require_relative './core_ext/modint.rb' # ModInt class ModInt < Numeric class << self def set_mod(mod) raise ArgumentError unless mod.is_a?(Integer) && (1 <= mod) $_mod = mod $_mod_is_prime = ModInt.prime?(mod) end def mod=(mod) set_mod mod end def mod $_mod end def raw(val) x = allocate x.val = val.to_i x end def prime?(n) return false if n <= 1 return true if (n == 2) || (n == 7) || (n == 61) return false if (n & 1) == 0 d = n - 1 d >>= 1 while (d & 1) == 0 [2, 7, 61].each do |a| t = d y = a.pow(t, n) while (t != n - 1) && (y != 1) && (y != n - 1) y = y * y % n t <<= 1 end return false if (y != n - 1) && ((t & 1) == 0) end true end def inv_gcd(a, b) a %= b return [b, 0] if a == 0 s, t = b, a m0, m1 = 0, 1 while t != 0 u = s / t s -= t * u m0 -= m1 * u s, t = t, s m0, m1 = m1, m0 end m0 += b / s if m0 < 0 [s, m0] end end attr_accessor :val alias to_i val def initialize(val = 0) @val = val.to_i % $_mod end def inc! @val += 1 @val = 0 if @val == $_mod self end def dec! @val = $_mod if @val == 0 @val -= 1 self end def add!(other) @val = (@val + other.to_i) % $_mod self end def sub!(other) @val = (@val - other.to_i) % $_mod self end def mul!(other) @val = @val * other.to_i % $_mod self end def div!(other) mul! inv_internal(other.to_i) end def +@ self end def -@ ModInt.raw($_mod - @val) end def **(other) $_mod == 1 ? 0 : ModInt.raw(@val.pow(other, $_mod)) end alias pow ** def inv ModInt.raw(inv_internal(@val) % $_mod) end def coerce(other) [ModInt(other), self] end def +(other) dup.add! other end def -(other) dup.sub! other end def *(other) dup.mul! other end def /(other) dup.div! other end def ==(other) @val == other.to_i end def pred dup.add!(-1) end def succ dup.add! 1 end def zero? @val == 0 end def dup ModInt.raw(@val) end def to_int @val end def to_s @val.to_s end def inspect "#{@val} mod #{$_mod}" end private def inv_internal(a) if $_mod_is_prime raise(RangeError, 'no inverse') if a == 0 a.pow($_mod - 2, $_mod) else g, x = ModInt.inv_gcd(a, $_mod) g == 1 ? x : raise(RangeError, 'no inverse') end end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
def floor_sum(n, m, a, b) raise ArgumentError if n < 0 || m < 1 res = 0 if a < 0 a2 = a % m res -= n * (n - 1) / 2 * ((a2 - a) / m) a = a2 end if b < 0 b2 = b % m res -= n * ((b2 - b) / m) b = b2 end res + floor_sum_unsigned(n, m, a, b) end def floor_sum_unsigned(n, m, a, b) res = 0 while true if a >= m res += n * (n - 1) / 2 * (a / m) a %= m end if b >= m res += n * (b / m) b %= m end y_max = a * n + b break if y_max < m n = y_max / m b = y_max % m m, a = a, m end res end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Segment Tree class Segtree attr_reader :d, :op, :n, :leaf_size, :log # new(v, e){ |x, y| } # new(v, op, e) def initialize(a0, a1, a2 = nil, &block) if a2.nil? @e, @op = a1, proc(&block) v = (a0.is_a?(Array) ? a0 : [@e] * a0) else @op, @e = a1, a2 v = (a0.is_a?(Array) ? a0 : [@e] * a0) end @n = v.size @log = (@n - 1).bit_length @leaf_size = 1 << @log @d = Array.new(@leaf_size * 2, @e) v.each_with_index { |v_i, i| @d[@leaf_size + i] = v_i } (@leaf_size - 1).downto(1) { |i| update(i) } end def set(q, x) q += @leaf_size @d[q] = x 1.upto(@log) { |i| update(q >> i) } end alias []= set def get(pos) @d[@leaf_size + pos] end alias [] get def prod(l, r = nil) if r.nil? # if 1st argument l is Range if r = l.end r += @n if r < 0 r += 1 unless l.exclude_end? else r = @n end l = l.begin l += @n if l < 0 end return @e if l == r sml = @e smr = @e l += @leaf_size r += @leaf_size while l < r if l[0] == 1 sml = @op.call(sml, @d[l]) l += 1 end if r[0] == 1 r -= 1 smr = @op.call(@d[r], smr) end l /= 2 r /= 2 end @op.call(sml, smr) end def all_prod @d[1] end def max_right(l, &block) return @n if l == @n f = proc(&block) l += @leaf_size sm = @e loop do l /= 2 while l.even? unless f.call(@op.call(sm, @d[l])) while l < @leaf_size l *= 2 if f.call(@op.call(sm, @d[l])) sm = @op.call(sm, @d[l]) l += 1 end end return l - @leaf_size end sm = @op.call(sm, @d[l]) l += 1 break if (l & -l) == l end @n end def min_left(r, &block) return 0 if r == 0 f = proc(&block) r += @leaf_size sm = @e loop do r -= 1 r /= 2 while r > 1 && r.odd? unless f.call(@op.call(@d[r], sm)) while r < @leaf_size r = r * 2 + 1 if f.call(@op.call(@d[r], sm)) sm = @op.call(@d[r], sm) r -= 1 end end return r + 1 - @leaf_size end sm = @op.call(@d[r], sm) break if (r & -r) == r end 0 end def update(k) @d[k] = @op.call(@d[2 * k], @d[2 * k + 1]) end # def inspect # for debug # t = 0 # res = "Segtree @e = #{@e}, @n = #{@n}, @leaf_size = #{@leaf_size} @op = #{@op}\n " # a = @d[1, @d.size - 1] # a.each_with_index do |e, i| # res << e.to_s << ' ' # if t == i && i < @leaf_size # res << "\n " # t = t * 2 + 2 # end # end # res # end end SegTree = Segtree
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# MaxFlowGraph class MaxFlow def initialize(n) @n = n @pos = [] @g = Array.new(n) { [] } end def add_edge(from, to, cap) edge_number = @pos.size @pos << [from, @g[from].size] from_id = @g[from].size to_id = @g[to].size to_id += 1 if from == to @g[from] << [to, to_id, cap] @g[to] << [from, from_id, 0] edge_number end def add_edges(edges) edges.each{ |from, to, cap| add_edge(from, to, cap) } self end def add(x, to = nil, cap = nil) cap ? add_edge(x, to, cap) : add_edges(x) end def push(edge) add_edge(*edge) end alias << push # return edge = [from, to, cap, flow] def [](i) from, from_id = @pos[i] to, to_id, cap = @g[from][from_id] # edge _from, _from_id, flow = @g[to][to_id] # reverse edge [from, to, cap + flow, flow] end alias get_edge [] alias edge [] def edges @pos.map do |(from, from_id)| to, to_id, cap = @g[from][from_id] _from, _from_id, flow = @g[to][to_id] [from, to, cap + flow, flow] end end def change_edge(i, new_cap, new_flow) from, from_id = @pos[i] e = @g[from][from_id] re = @g[e[0]][e[1]] e[2] = new_cap - new_flow re[2] = new_flow end def flow(s, t, flow_limit = 1 << 64) flow = 0 while flow < flow_limit level = bfs(s, t) break if level[t] == -1 iter = [0] * @n while flow < flow_limit f = dfs(t, flow_limit - flow, s, level, iter) break if f == 0 flow += f end end flow end alias max_flow flow def min_cut(s) visited = Array.new(@n, false) que = [s] while (q = que.shift) visited[q] = true @g[q].each do |(to, _rev, cap)| if cap > 0 && !visited[to] visited[to] = true que << to end end end visited end private def bfs(s, t) level = Array.new(@n, -1) level[s] = 0 que = [s] while (v = que.shift) @g[v].each do |u, _, cap| next if cap == 0 || level[u] >= 0 level[u] = level[v] + 1 return level if u == t que << u end end level end def dfs(v, up, s, level, iter) return up if v == s res = 0 level_v = level[v] while iter[v] < @g[v].size i = iter[v] e = @g[v][i] cap = @g[e[0]][e[1]][2] if level_v > level[e[0]] && cap > 0 d = dfs(e[0], (up - res < cap ? up - res : cap), s, level, iter) if d > 0 @g[v][i][2] += d @g[e[0]][e[1]][2] -= d res += d break if res == up end end iter[v] += 1 end res end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Disjoint Set Union class DSU def initialize(n = 0) @n = n @parent_or_size = Array.new(n, -1) # root node: -1 * component size # otherwise: parent end attr_reader :parent_or_size, :n def merge(a, b) x = leader(a) y = leader(b) return x if x == y x, y = y, x if -@parent_or_size[x] < -@parent_or_size[y] @parent_or_size[x] += @parent_or_size[y] @parent_or_size[y] = x end alias unite merge def same?(a, b) leader(a) == leader(b) end alias same same? def leader(a) unless 0 <= a && a < @n raise ArgumentError.new, "#{a} is out of range (0...#{@n})" end @parent_or_size[a] < 0 ? a : (@parent_or_size[a] = leader(@parent_or_size[a])) end alias root leader alias find leader def [](a) if @n <= a @parent_or_size.concat([-1] * (a - @n + 1)) @n = @parent_or_size.size end @parent_or_size[a] < 0 ? a : (@parent_or_size[a] = self[@parent_or_size[a]]) end def size(a) -@parent_or_size[leader(a)] end def groups (0 ... @parent_or_size.size).group_by{ |i| leader(i) }.values end def to_s "<#{self.class}: @n=#{@n}, #{@parent_or_size}>" end end UnionFind = DSU
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# induce sort (internal method) def sa_is_induce(s, ls, sum_l, sum_s, lms) n = s.size sa = [-1] * n buf = sum_s.dup lms.each{ |lms| if lms != n sa[buf[s[lms]]] = lms buf[s[lms]] += 1 end } buf = sum_l.dup sa[buf[s[-1]]] = n - 1 buf[s[-1]] += 1 sa.each{ |v| if v >= 1 && !ls[v - 1] sa[buf[s[v - 1]]] = v - 1 buf[s[v - 1]] += 1 end } buf = sum_l.dup sa.reverse_each{ |v| if v >= 1 && ls[v - 1] buf[s[v - 1] + 1] -= 1 sa[buf[s[v - 1] + 1]] = v - 1 end } return sa end # SA-IS (internal method) def sa_is(s, upper) n = s.size return [] if n == 0 return [0] if n == 1 ls = [false] * n (n - 2).downto(0){ |i| ls[i] = (s[i] == s[i + 1] ? ls[i + 1] : s[i] < s[i + 1]) } sum_l = [0] * (upper + 1) sum_s = [0] * (upper + 1) n.times{ |i| if ls[i] sum_l[s[i] + 1] += 1 else sum_s[s[i]] += 1 end } 0.upto(upper){ |i| sum_s[i] += sum_l[i] sum_l[i + 1] += sum_s[i] if i < upper } lms = (1 ... n).select{ |i| !ls[i - 1] && ls[i] } m = lms.size lms_map = [-1] * (n + 1) lms.each_with_index{ |lms, id| lms_map[lms] = id } sa = sa_is_induce(s, ls, sum_l, sum_s, lms) return sa if m == 0 sorted_lms = sa.select{ |sa| lms_map[sa] != -1 } rec_s = [0] * m rec_upper = 0 rec_s[lms_map[sorted_lms[0]]] = 0 1.upto(m - 1) do |i| l, r = sorted_lms[i - 1, 2] end_l = lms[lms_map[l] + 1] || n end_r = lms[lms_map[r] + 1] || n same = true if end_l - l == end_r - r while l < end_l break if s[l] != s[r] l += 1 r += 1 end same = false if l == n || s[l] != s[r] else same = false end rec_upper += 1 if not same rec_s[lms_map[sorted_lms[i]]] = rec_upper end sa_is(rec_s, rec_upper).each_with_index{ |rec_sa, id| sorted_lms[id] = lms[rec_sa] } return sa_is_induce(s, ls, sum_l, sum_s, sorted_lms) end # suffix array for array of integers or string def suffix_array(s, upper = nil) if upper s.each{ |s| raise ArgumentError if s < 0 || upper < s } else case s when Array # compression n = s.size idx = (0 ... n).sort_by{ |i| s[i] } t = [0] * n upper = 0 t[idx[0]] = 0 1.upto(n - 1){ |i| upper += 1 if s[idx[i - 1]] != s[idx[i]] t[idx[i]] = upper } s = t when String upper = 255 s = s.bytes end end return sa_is(s, upper) end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# this implementation is different from ACL because of calculation time # ref : https://snuke.hatenablog.com/entry/2014/12/03/214243 # ACL implementation : https://atcoder.jp/contests/abc135/submissions/18836384 (731ms) # this implementation : https://atcoder.jp/contests/abc135/submissions/18836378 (525ms) def z_algorithm(s) n = s.size return [] if n == 0 s = s.codepoints if s.is_a?(String) z = [0] * n z[0] = n i, j = 1, 0 while i < n j += 1 while i + j < n && s[j] == s[i + j] z[i] = j if j == 0 i += 1 next end k = 1 while i + k < n && k + z[k] < j z[i + k] = z[k] k += 1 end i += k j -= k end return z end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# return [rem, mod] or [0, 0] (if no solution) def crt(r, m) unless r.size == m.size raise ArgumentError.new("size of r and m must be equal for crt(r, m)") end n = r.size r0, m0 = 0, 1 n.times do |i| raise ArgumentError if m[i] < 1 r1, m1 = r[i] % m[i], m[i] if m0 < m1 r0, r1 = r1, r0 m0, m1 = m1, m0 end if m0 % m1 == 0 return [0, 0] if r0 % m1 != r1 next end g, im = inv_gcd(m0, m1) u1 = m1 / g return [0, 0] if (r1 - r0) % g != 0 x = (r1 - r0) / g * im % u1 r0 += x * m0 m0 *= u1 r0 += m0 if r0 < 0 end return [r0, m0] end # internal method # return [g, x] s.t. g = gcd(a, b), x*a = g (mod b), 0 <= x < b/g def inv_gcd(a, b) a %= b return [b, 0] if a == 0 s, t = b, a m0, m1 = 0, 1 while t > 0 u, s = s.divmod(t) m0 -= m1 * u s, t = t, s m0, m1 = m1, m0 end m0 += b / s if m0 < 0 return [s, m0] end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
require_relative './scc.rb' # TwoSAT # Reference: https://github.com/atcoder/ac-library/blob/master/atcoder/twosat.hpp class TwoSAT def initialize(n) @n = n @answer = Array.new(n) @scc = SCC.new(2 * n) end attr_reader :answer def add_clause(i, f, j, g) unless 0 <= i && i < @n && 0 <= j && j < @n raise ArgumentError.new("i:#{i} and j:#{j} must be in (0...#{@n})") end @scc.add_edge(2 * i + (f ? 0 : 1), 2 * j + (g ? 1 : 0)) @scc.add_edge(2 * j + (g ? 0 : 1), 2 * i + (f ? 1 : 0)) nil end def satisfiable? id = @scc.send(:scc_ids)[1] @n.times do |i| return false if id[2 * i] == id[2 * i + 1] @answer[i] = id[2 * i] < id[2 * i + 1] end true end alias satisfiable satisfiable? end TwoSat = TwoSAT
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
def ModInt(val) ModInt.new(val) end # Integer class Integer def to_modint ModInt.new(self) end alias to_m to_modint end # String class String def to_modint ModInt.new(to_i) end alias to_m to_modint end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
class Array def to_fenwick_tree FenwickTree.new(self) end alias to_fetree to_fenwick_tree def to_priority_queue PriorityQueue.new(self) end alias to_pq to_priority_queue end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
require "prime" class Integer # Returns the positive divisors of +self+ if +self+ is positive. # # == Example # 6.divisors #=> [1, 2, 3, 6] # 7.divisors #=> [1, 7] # 8.divisors #=> [1, 2, 4, 8] def divisors if prime? [1, self] elsif self == 1 [1] else xs = prime_division.map{ |p, n| Array.new(n + 1){ |e| p**e } } x = xs.pop x.product(*xs).map{ |t| t.inject(:*) }.sort end end # Iterates the given block for each divisor of +self+. # # == Example # ds = [] # 10.divisors{ |d| ds << d } # ds #=> [1, 2, 5, 10] def each_divisor(&block) block_given? ? divisors.each(&block) : enum_for(:each_divisor) end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
module AcLibraryRb VERSION = "1.2.0".freeze end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/floor_sum.rb' def floor_sum_naive(n, m, a, b) res = 0 n.times do |i| z = a * i + b res += (z - z % m) / m end res end class FloorSumTest < Minitest::Test def test_floor_sum k = 5 (0..k).each do |n| (1..k).each do |m| (-k..k).each do |a| (-k..k).each do |b| assert_equal floor_sum_naive(n, m, a, b), floor_sum(n, m, a, b) end end end end end # https://atcoder.jp/contests/practice2/tasks/practice2_c def test_atcoder_library_practice_contest assert_equal 3, floor_sum(4, 10, 6, 3) assert_equal 13, floor_sum(6, 5, 4, 3) assert_equal 0, floor_sum(1, 1, 0, 0) assert_equal 314_095_480, floor_sum(31_415, 92_653, 58_979, 32_384) assert_equal 499_999_999_500_000_000, floor_sum(1_000_000_000, 1_000_000_000, 999_999_999, 999_999_999) end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/fenwick_tree.rb' class FenwickTreeTest < Minitest::Test def test_practice_contest a = [1, 2, 3, 4, 5] ft = FenwickTree.new(a) assert_equal 15, ft.sum(0, 5) assert_equal 7, ft.sum(2, 4) ft.add(3, 10) assert_equal 25, ft.sum(0, 5) assert_equal 6, ft.sum(0, 3) end def test_empty assert_raises(ArgumentError){ FenwickTree.new } end def test_zero fw = FenwickTree.new(0) assert_equal 0, fw.sum(0, 0) end def test_naive (1 .. 20).each do |n| fw = FenwickTree.new(n) n.times { |i| fw.add(i, i * i) } (0 .. n).each do |l| (l .. n).each do |r| sum = 0 (l ... r).each { |i| sum += i * i } assert_equal sum, fw.sum(l, r) end end end end def test_init n = 10 a = Array.new(n) { |i| i } fwa = FenwickTree.new(a) fwi = FenwickTree.new(n) a.each_with_index { |e, i| fwi.add(i, e) } assert_equal fwi.data, fwa.data end def test_invalid_init assert_raises(ArgumentError){ FenwickTree.new(:invalid_argument) } end def test_experimental_sum a = [1, 2, 3, 4, 5] ft = FenwickTree.new(a) assert_equal 15, ft.sum(0...5) assert_equal 15, ft.sum(0..4) assert_equal 15, ft.sum(0..) assert_equal 15, ft.sum(0..-1) assert_equal 10, ft.sum(0...-1) assert_equal 7, ft.sum(2...4) assert_equal 7, ft.sum(2..3) ft.add(3, 10) assert_equal 25, ft.sum(0...5) assert_equal 25, ft.sum(0..4) assert_equal 25, ft.sum(5) assert_equal 6, ft.sum(3) end def test_to_s uft = FenwickTree.new([1, 2, 4, 8]) assert_equal "<FenwickTree: @size=4, (1, 3, 4, 15)>", uft.to_s end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/suffix_array.rb' require_relative '../lib/lcp_array.rb' def lcp_array_naive(s) s = s.bytes if s.is_a?(String) n = s.size return (0 ... n).map{ |i| s[i..-1] }.sort.each_cons(2).map{ |s, t| lcp = 0 lcp += 1 while lcp < s.size && lcp < t.size && s[lcp] == t[lcp] lcp } end class LcpArrayTest < Minitest::Test def test_random_array_small_elements max_num = 5 20.times{ a = (0 ... 30).map{ rand(-max_num .. max_num) } assert_equal lcp_array_naive(a), lcp_array(a, suffix_array(a)) } end def test_random_array_big_elements max_num = 10**18 20.times{ a = (0 ... 30).map{ rand(-max_num .. max_num) } assert_equal lcp_array_naive(a), lcp_array(a, suffix_array(a)) } end def test_random_string 20.times{ s = (0 ... 30).map{ rand(' '.ord .. '~'.ord).chr }.join assert_equal lcp_array_naive(s), lcp_array(s, suffix_array(s)) } end def test_mississippi s = "mississippi" assert_equal lcp_array_naive(s), lcp_array(s, suffix_array(s)) end def test_abracadabra s = "abracadabra" assert_equal lcp_array_naive(s), lcp_array(s, suffix_array(s)) end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
require 'minitest' require 'minitest/autorun' require_relative '../lib/deque.rb' class DequeTest < Minitest::Test def test_new assert_equal Deque.new, Deque[] assert_equal Deque.new([]), Deque[] assert_equal Deque.new([1, 2, 3]), Deque[1, 2, 3] assert_equal Deque.new([5, 5, 5]), Deque.new(3, 5) end def test_size d = Deque[] assert_equal 0, d.size d.pop assert_equal 0, d.size d.shift assert_equal 0, d.size d.push(2) assert_equal 1, d.size d.unshift(nil) assert_equal 2, d.size d.push('a') assert_equal 3, d.size d.pop assert_equal 2, d.size d.shift assert_equal 1, d.size end def test_empty? d = Deque[] assert d.empty? d.push(1) refute d.empty? d = Deque[1, 2, 3] refute d.empty? d.shift d.pop d.shift assert d.empty? end def test_unshift d = Deque[] assert_equal Deque[1], d.unshift(1) assert_equal Deque[2, 1], d.unshift(2) assert_equal Deque[3, 2, 1], d.prepend(3) end def test_push d = Deque[1, 2, 3] assert_equal Deque[1, 2, 3, 4], d.push(4) assert_equal Deque[1, 2, 3, 4, 5, 6], d.push(5, 6) d.unshift(99) d.unshift(98) assert_equal Deque[98, 99, 1, 2, 3, 4, 5, 6], d end def test_pop d = Deque[1, 2, 3] assert_equal 3, d.last assert_equal 3, d.pop assert_equal 2, d.pop assert_equal 1, d.pop end def test_pop_empty d = Deque[] assert_nil d.pop end def test_shift d = Deque[1, 2, 3] assert_equal 1, d.shift assert_equal 2, d.shift assert_equal 3, d.shift end def test_empty_shift d = Deque[1, 2, 3] assert_equal 1, d.shift assert_equal 2, d.shift assert_equal 3, d.shift assert_nil d.shift assert_nil d.shift d = Deque[] assert_nil d.shift assert_nil d.shift end def test_slice1 d = Deque[:a, :b, :c, :d] assert_equal :d, d.slice(-1) assert_equal :d, d[-1] assert_equal :a, d[-4] assert_equal :b, d[1] assert_equal :b, d.at(1) assert_equal :c, d[2] d.push(:e) d.unshift(:z) assert_equal :a, d[1] end def test_slice_out_of_range d = Deque[] assert_nil d[0] assert_nil d[-1] end def test_slice_range d = Deque[:a, :b, :c, :d] assert_equal Deque[:b, :c], d[1..2] assert_equal Deque[:b, :c], d[1...3] assert_equal Deque[:d], d[-1..-1] d.shift assert_equal Deque[:c, :d], d[-2..-1] end def test_slice_assignment d = Deque[:a, :b, :c, :d] d[0] = 10 assert_equal Deque[10, :b, :c, :d], d d[-1] = 40 assert_equal Deque[10, :b, :c, 40], d d.pop d[-1] = 30 d.push(:x) assert_equal Deque[10, :b, 30, :x], d end def test_count assert_equal 0, Deque[].count assert_equal 1, Deque[nil].count assert_equal(1, Deque[1, 2].count{ |e| e >= 2 }) end def test_map assert_equal([2], Deque[1].map{ |e| e * 2 }) end def test_dig assert_nil Deque[].dig(1, 2, 3) assert_equal :b, Deque[:x, %i[a b c]].dig(1, 1) deque = Deque[1, Deque[2, 3]] assert_equal 3, deque.dig(1, 1) assert_raises(ArgumentError){ Deque[5, 6].dig } end def test_inspect deque = Deque.new([1, 2, 3]) assert_equal "Deque[1, 2, 3]", deque.inspect end def test_to_a assert_equal [], Deque[].to_a assert_equal [1, 2, 3], Deque[1, 2, 3].to_a d = Deque[] d.push(1) assert_equal [1], d.to_a d.unshift(2) assert_equal [2, 1], d.to_a end def test_to_a_with_reverse d = Deque.new.reverse assert_equal [], d.to_a d.reverse! assert_equal [], d.to_a d.push(2, 1) d.reverse! d.push(3) d.unshift(0) assert_equal [0, 1, 2, 3], d.to_a d.reverse! assert_equal [3, 2, 1, 0], d.to_a end def test_to_s assert_equal "Deque[]", Deque[].to_s assert_equal "Deque[1, 2, 3]", Deque[1, 2, 3].to_s assert_output("Deque[1, 2, 3]\n"){ puts Deque[1, 2, 3] } end def test_reverse d = Deque.new([5, 4, 2]) assert_equal Deque[2, 4, 5], d.reverse end def test_reverse! assert_equal Deque[], Deque[].reverse! assert_equal Deque[2, 1], Deque[1, 2].reverse! end def test_rotate! d = Deque["a", "b", "c", "d"] assert_equal Deque["b", "c", "d", "a"], d.rotate! assert_equal Deque["b", "c", "d", "a"], d assert_equal Deque["d", "a", "b", "c"], d.rotate!(2) assert_equal Deque["a", "b", "c", "d"], d.rotate!(-3) end def test_rotate_bang_with_reverse d = Deque["d", "c", "b", "a"].reverse assert_equal Deque["b", "c", "d", "a"], d.rotate! assert_equal Deque["b", "c", "d", "a"], d assert_equal Deque["d", "a", "b", "c"], d.rotate!(2) assert_equal Deque["a", "b", "c", "d"], d.rotate!(-3) end def test_rotate d = Deque["a", "b", "c", "d"] assert_equal Deque["b", "c", "d", "a"], d.rotate assert_equal Deque["a", "b", "c", "d"], d assert_equal Deque["c", "d", "a", "b"], d.rotate(2) assert_equal Deque["d", "a", "b", "c"], d.rotate(-1) assert_equal Deque["b", "c", "d", "a"], d.rotate(-3) end def test_rotate_with_reverse d = Deque[:d, :c, :b, :a].reverse assert_equal Deque[:b, :c, :d, :a], d.rotate assert_equal Deque[:a, :b, :c, :d], d assert_equal Deque[:c, :d, :a, :b], d.rotate(2) assert_equal Deque[:d, :a, :b, :c], d.rotate(-1) assert_equal Deque[:b, :c, :d, :a], d.rotate(-3) end def test_swap d = Deque["a", "b", "c", "d"] assert_equal Deque["a", "c", "b", "d"], d.swap(1, 2) assert_equal Deque["a", "d", "b", "c"], d.swap(1, 3) assert_equal Deque["c", "d", "b", "a"], d.swap(-4, -1) d.push("e") d.unshift("f") assert_equal Deque["e", "c", "d", "b", "a", "f"], d.swap(0, -1) end def test_sample d = Deque.new([100, 2, 3]) assert_includes [100, 2, 3], d.sample end def test_shuffle d = Deque.new([1, 2, 3, 4, 5]) s = d.shuffle assert_equal d.size, s.size assert_equal d.to_a.sort, s.to_a.sort end def test_replace d = Deque["a", "b", "c", "d"] a = Deque["a", "b", "c"] b = Deque[:a, :b] c = Deque[1, 2, 3] assert_equal a, d.replace(a) assert_equal b, d.replace(b) assert_equal c, d.replace(c) end def test_reverse_push d = Deque[2, 1] d.reverse! d.push(3) assert_equal Deque[1, 2, 3], d end def test_reverse_unshift d = Deque[2, 1] d.reverse! d.unshift(0) assert_equal Deque[0, 1, 2], d end def test_reverse_pop d = Deque[2, 1] d.reverse! assert_equal 2, d.pop assert_equal Deque[1], d end def test_reverse_shift d = Deque[2, 1] d.reverse! assert_equal 1, d.shift assert_equal Deque[2], d end def test_reverse_slice d = Deque[30, 20, 10, 0] d.reverse! assert_equal 0, d[0] assert_equal 20, d[2] assert_equal 30, d[-1] d.reverse! assert_equal 0, d[-1] end def test_reverse_each d = Deque[20, 10, 0] d.reverse! assert_equal [0, 10, 20], d.each.to_a end def test_slice2 d = Deque[:a, :b, :c, :d] assert_equal Deque[:b, :c], d[1, 2] assert_equal Deque[:d], d[-1, 1] d.shift assert_equal Deque[:c, :d], d[-2, 2] d = Deque[1, 2, 3] assert_equal Deque[], d[3, 1] end def test_slice_with_reverse d = Deque[:a, :b, :c, :d] d.reverse! assert_equal Deque[:c, :b], d[1, 2] assert_equal Deque[:a], d[-1, 1] d.shift assert_equal Deque[:b, :a], d[-2, 2] end def test_each_when_head_is_bigger_than_tail d = Deque.new([1, 2]) d.unshift(0) ret = [] d.each { |e| ret << e } assert_equal [0, 1, 2], ret d.reverse! ret = [] d.each { |e| ret << e } assert_equal [2, 1, 0], ret end def test_range d = Deque[:a, :b, :c, :d] d.reverse! assert_equal Deque[:c, :b], d[1..2] assert_equal Deque[:c, :b], d[1...3] assert_equal Deque[:a], d[-1..-1] d.shift assert_equal Deque[:b, :a], d[-2..-1] end def test_join d = Deque[:x, :y, :z] assert_equal "xyz", d.join assert_equal "x, y, z", d.join(", ") end def test_hash assert_equal Deque[].hash, Deque[].hash assert_equal Deque[1].hash, Deque[1].hash assert_equal Deque[1, 2].hash, Deque[1, 2].hash assert_equal Deque[1, 2, 3].hash, Deque[1, 2, 3].hash refute_equal Deque[1].hash, Deque[2].hash refute_equal Deque[1, 2].hash, Deque[2, 1].hash refute_equal Deque[1, 2, 3].hash, Deque[3, 2, 1].hash end def test_clear d = Deque[:a, :b, :c, :d] d.clear assert_equal 0, d.size assert_equal Deque.new, d end def test_typical90_ar_044_example1 deq = Deque[6, 17, 2, 4, 17, 19, 1, 7] deq.unshift(deq.pop) deq[6], deq[1] = deq[1], deq[6] deq[1], deq[5] = deq[5], deq[1] deq[3], deq[4] = deq[4], deq[3] assert_equal 4, deq[3] end def test_typical90_ar_044_example2 deq = Deque[16, 7, 10, 2, 9, 18, 15, 20, 5] deq.unshift(deq.pop) deq[0], deq[3] = deq[3], deq[0] deq.unshift(deq.pop) deq[7], deq[4] = deq[4], deq[7] deq.unshift(deq.pop) assert_equal 18, deq[5] end def test_typical90_ar_044_example3 deq = Deque[23, 92, 85, 34, 21, 63, 12, 9, 81, 44, 96] assert_equal 44, deq[9] assert_equal 21, deq[4] deq[2], deq[3] = deq[3], deq[2] deq.unshift(deq.pop) deq[3], deq[10] = deq[10], deq[3] assert_equal 34, deq[10] deq[2], deq[4] = deq[4], deq[2] deq.unshift(deq.pop) deq.unshift(deq.pop) assert_equal 63, deq[8] deq.unshift(deq.pop) assert_equal 85, deq[5] assert_equal 63, deq[9] deq.unshift(deq.pop) assert_equal 21, deq[9] assert_equal 34, deq[3] assert_equal 96, deq[4] end def test_typical90_ar_044_example1_details deq = Deque[6, 17, 2, 4, 17, 19, 1, 7] deq.unshift(deq.pop) assert_equal Deque[7, 6, 17, 2, 4, 17, 19, 1], deq deq[6], deq[1] = deq[1], deq[6] assert_equal Deque[7, 19, 17, 2, 4, 17, 6, 1], deq deq[1], deq[5] = deq[5], deq[1] assert_equal Deque[7, 17, 17, 2, 4, 19, 6, 1], deq deq[3], deq[4] = deq[4], deq[3] assert_equal Deque[7, 17, 17, 4, 2, 19, 6, 1], deq assert_equal 4, deq[3] end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/max_flow.rb' class MaxFlowTest < Minitest::Test def test_simple g = MaxFlow.new(4) assert_equal 0, g.add_edge(0, 1, 1) assert_equal 1, g.add_edge(0, 2, 1) assert_equal 2, g.add_edge(1, 3, 1) assert_equal 3, g.add_edge(2, 3, 1) assert_equal 4, g.add_edge(1, 2, 1) assert_equal 2, g.flow(0, 3) edges = [ [0, 1, 1, 1], [0, 2, 1, 1], [1, 3, 1, 1], [2, 3, 1, 1], [1, 2, 1, 0] ] edges.each_with_index do |edge, i| assert_equal edge, g.get_edge(i) assert_equal edge, g.edge(i) assert_equal edge, g[i] end assert_equal edges, g.edges assert_equal [true, false, false, false], g.min_cut(0) end def test_not_simple g = MaxFlow.new(2) assert_equal 0, g.add_edge(0, 1, 1) assert_equal 1, g.add_edge(0, 1, 2) assert_equal 2, g.add_edge(0, 1, 3) assert_equal 3, g.add_edge(0, 1, 4) assert_equal 4, g.add_edge(0, 1, 5) assert_equal 5, g.add_edge(0, 0, 6) assert_equal 6, g.add_edge(1, 1, 7) assert_equal 15, g.flow(0, 1) assert_equal [0, 1, 1, 1], g.get_edge(0) assert_equal [0, 1, 2, 2], g.get_edge(1) assert_equal [0, 1, 3, 3], g.get_edge(2) assert_equal [0, 1, 4, 4], g.get_edge(3) assert_equal [0, 1, 5, 5], g.get_edge(4) assert_equal [true, false], g.min_cut(0) end def test_cut g = MaxFlow.new(3) assert_equal 0, g.add_edge(0, 1, 2) assert_equal 1, g.add_edge(1, 2, 1) assert_equal 1, g.flow(0, 2) assert_equal [0, 1, 2, 1], g[0] assert_equal [1, 2, 1, 1], g[1] assert_equal [true, true, false], g.min_cut(0) end def test_twice g = MaxFlow.new(3) assert_equal 0, g.add_edge(0, 1, 1) assert_equal 1, g.add_edge(0, 2, 1) assert_equal 2, g.add_edge(1, 2, 1) assert_equal 2, g.max_flow(0, 2) assert_equal [0, 1, 1, 1], g.edge(0) assert_equal [0, 2, 1, 1], g.edge(1) assert_equal [1, 2, 1, 1], g.edge(2) g.change_edge(0, 100, 10) assert_equal [0, 1, 100, 10], g.edge(0) assert_equal 0, g.max_flow(0, 2) assert_equal 90, g.max_flow(0, 1) assert_equal [0, 1, 100, 100], g.edge(0) assert_equal [0, 2, 1, 1], g.edge(1) assert_equal [1, 2, 1, 1], g.edge(2) assert_equal 2, g.max_flow(2, 0) assert_equal [0, 1, 100, 99], g.edge(0) assert_equal [0, 2, 1, 0], g.edge(1) assert_equal [1, 2, 1, 0], g.edge(2) end def test_typical_mistake n = 100 g = MaxFlow.new(n) s, a, b, c, t = *0..4 uv = [5, 6] g.add_edge(s, a, 1) g.add_edge(s, b, 2) g.add_edge(b, a, 2) g.add_edge(c, t, 2) uv.each { |x| g.add_edge(a, x, 3) } loop do next_uv = uv.map { |x| x + 2 } break if next_uv[1] >= n uv.each do |x| next_uv.each do |y| g.add_edge(x, y, 3) end end uv = next_uv end uv.each { |x| g.add_edge(x, c, 3) } assert_equal 2, g.max_flow(s, t) end # https://github.com/atcoder/ac-library/issues/1 # https://twitter.com/Mi_Sawa/status/1303170874938331137 def test_self_loop g = MaxFlow.new(3) assert_equal 0, g.add_edge(0, 0, 100) assert_equal [0, 0, 100, 0], g.edge(0) end # https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/6/GRL_6_A def test_aizu_grl6_a g = MaxFlow.new(5) assert_equal 0, g.add_edge(0, 1, 2) assert_equal 1, g.add_edge(0, 2, 1) assert_equal 2, g.add_edge(1, 2, 1) assert_equal 3, g.add_edge(1, 3, 1) assert_equal 4, g.add_edge(2, 3, 2) assert_equal 3, g.max_flow(0, 4 - 1) end def test_arihon_antsbook_3_5 g = MaxFlow.new(5) assert_equal 0, g.add_edge(0, 1, 10) assert_equal 1, g.add_edge(0, 2, 2) assert_equal 2, g.add_edge(1, 2, 6) assert_equal 3, g.add_edge(1, 3, 6) assert_equal 4, g.add_edge(2, 4, 5) assert_equal 5, g.add_edge(3, 2, 3) assert_equal 6, g.add_edge(3, 4, 8) assert_equal 11, g.max_flow(0, 4) end # https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/6/GRL_6_A def test_push g = MaxFlow.new(5) assert_equal 0, g << [0, 1, 2] assert_equal 1, g << [0, 2, 1] assert_equal 2, g << [1, 2, 1] assert_equal 3, g << [1, 3, 1] assert_equal 4, g << [2, 3, 2] assert_equal 3, g.max_flow(0, 4 - 1) end def test_add_edges g = MaxFlow.new(3) g.add([[0, 1, 2], [1, 2, 1]]) assert_equal 1, g.flow(0, 2) assert_equal [0, 1, 2, 1], g[0] assert_equal [1, 2, 1, 1], g[1] assert_equal [true, true, false], g.min_cut(0) end def test_constructor_error assert_raises(ArgumentError){ MaxFlow.new } end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/two_sat.rb' def solve(two_sat, count, distance, x, y) count.times do |i| (i + 1...count).each do |j| two_sat.add_clause(i, false, j, false) if (x[i] - x[j]).abs < distance two_sat.add_clause(i, false, j, true) if (x[i] - y[j]).abs < distance two_sat.add_clause(i, true, j, false) if (y[i] - x[j]).abs < distance two_sat.add_clause(i, true, j, true) if (y[i] - y[j]).abs < distance end end two_sat end class TwoSATTest < Minitest::Test def test_empty assert_raises(ArgumentError){ TwoSAT.new } ts1 = TwoSAT.new(0) assert_equal true, ts1.satisfiable assert_equal [], ts1.answer end def test_one ts = TwoSAT.new(1) ts.add_clause(0, true, 0, true) ts.add_clause(0, false, 0, false) assert_equal false, ts.satisfiable ts = TwoSAT.new(1) ts.add_clause(0, true, 0, true) assert_equal true, ts.satisfiable assert_equal [true], ts.answer ts = TwoSAT.new(1) ts.add_clause(0, false, 0, false) assert_equal true, ts.satisfiable assert_equal [false], ts.answer end # https://atcoder.jp/contests/practice2/tasks/practice2_h def test_atcoder_library_practice_contest_case_one count, distance = 3, 2 x = [1, 2, 0] y = [4, 5, 6] two_sat = solve(TwoSAT.new(count), count, distance, x, y) assert_equal true, two_sat.satisfiable assert_equal [false, true, true], two_sat.answer end def test_atcoder_library_practice_contest_case_two count, distance = 3, 3 x = [1, 2, 0] y = [4, 5, 6] two_sat = solve(TwoSAT.new(count), count, distance, x, y) assert_equal false, two_sat.satisfiable end def test_alias_satisfiable? ts1 = TwoSAT.new(0) assert_equal true, ts1.satisfiable? assert_equal [], ts1.answer end def test_error ts1 = TwoSAT.new(2) assert_raises(ArgumentError){ ts1.add_clause(0, true, 2, false) } assert_raises(ArgumentError){ ts1.add_clause(2, true, 0, false) } end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
begin require 'simplecov' SimpleCov.start if ENV['GITHUB_ACTIONS'] == 'true' require 'simplecov-cobertura' SimpleCov.formatter = SimpleCov::Formatter::CoberturaFormatter end rescue LoadError puts "[INFO] You can use simplecov gem for this test!" end require_relative 'convolution_test' require_relative 'crt_test' require_relative 'deque_test' require_relative 'dsu_test' require_relative 'fenwick_tree_test' require_relative 'floor_sum_test' require_relative 'inv_mod_test' require_relative 'lazy_segtree_test' require_relative 'lcp_array_test' require_relative 'max_flow_test' require_relative 'min_cost_flow_test' require_relative 'modint_test' require_relative 'pow_mod_test' require_relative 'priority_queue_test' require_relative 'scc_test' require_relative 'segtree_test' require_relative 'suffix_array_test' require_relative 'two_sat_test' require_relative 'z_algorithm_test' require_relative "../lib/ac-library-rb/version" class AcLibraryRbTest < Minitest::Test def test_that_it_has_a_version_number refute_nil ::AcLibraryRb::VERSION end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/pow_mod.rb' def naive_pow_mod(x, n, mod) y = x % mod z = 1 % mod n.times { z = (z * y) % mod } z end class PowModTest < Minitest::Test def test_prime_mod (-5 .. 5).each do |a| (0 .. 5).each do |b| (2 .. 10).each do |c| assert_equal naive_pow_mod(a, b, c), pow_mod(a, b, c) # assert_equal naive_pow_mod(a, b, c), a.pow(b, c) end end end end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/min_cost_flow.rb' # Test for MinCostFlow class MinCostFlowTest < Minitest::Test def test_simple g = MinCostFlow.new(4) g.add_edge(0, 1, 1, 1) g.add_edge(0, 2, 1, 1) g.add_edge(1, 3, 1, 1) g.add_edge(2, 3, 1, 1) g.add_edge(1, 2, 1, 1) assert_equal [[0, 0], [2, 4]], g.slope(0, 3, 10) edges = [ [0, 1, 1, 1, 1], [0, 2, 1, 1, 1], [1, 3, 1, 1, 1], [2, 3, 1, 1, 1], [1, 2, 1, 0, 1] ] edges.each_with_index { |edge, i| assert_equal edge, g.get_edge(i) } assert_equal edges, g.edges end def test_usage g = MinCostFlow.new(2) g.add_edge(0, 1, 1, 2) assert_equal [1, 2], g.flow(0, 1) g = MinCostFlow.new(2) g.add_edge(0, 1, 1, 2) assert_equal [[0, 0], [1, 2]], g.slope(0, 1) end def test_self_loop g = MinCostFlow.new(3) assert_equal 0, g.add_edge(0, 0, 100, 123) assert_equal [0, 0, 100, 0, 123], g.get_edge(0) assert_equal [0, 0, 100, 0, 123], g.edge(0) assert_equal [0, 0, 100, 0, 123], g[0] end def test_same_cost_paths g = MinCostFlow.new(3) assert_equal 0, g.add_edge(0, 1, 1, 1) assert_equal 1, g.add_edge(1, 2, 1, 0) assert_equal 2, g.add_edge(0, 2, 2, 1) assert_equal [[0, 0], [3, 3]], g.slope(0, 2) end def test_add_edges g = MinCostFlow.new(3) edges = [[0, 1, 1, 1], [1, 2, 1, 0], [0, 2, 2, 1]] g.add(edges) assert_equal [[0, 0], [3, 3]], g.slope(0, 2) end def test_only_one_nonzero_cost_edge g = MinCostFlow.new(2) g.add_edge(0, 1, 1, 100) assert_equal [1, 100], g.flow(0, 1, 1) g = MinCostFlow.new(3) g.add_edge(0, 1, 1, 1) g.add_edge(1, 2, 1, 0) assert_equal [[0, 0], [1, 1]], g.slope(0, 2) end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/scc.rb' class SCCTest < Minitest::Test def test_empty assert_raises(ArgumentError){ SCC.new } graph1 = SCC.new(0) assert_equal [], graph1.scc end def test_simple graph = SCC.new(2) graph.add_edge(0, 1) graph.add_edge(1, 0) scc = graph.scc assert_equal 1, scc.size end def test_self_loop graph = SCC.new(2) graph.add_edge(0, 0) graph.add_edge(0, 0) graph.add_edge(1, 1) scc = graph.scc assert_equal 2, scc.size end def test_practice graph = SCC.new(6) edges = [[1, 4], [5, 2], [3, 0], [5, 5], [4, 1], [0, 3], [4, 2]] edges.each { |x, y| graph.add_edge(x, y) } groups = graph.scc assert_equal 4, groups.size assert_equal [5], groups[0] assert_equal [4, 1].sort, groups[1].sort assert_equal [2], groups[2] assert_equal [3, 0].sort, groups[3].sort end def test_typical90_021 graph = SCC.new(4) edges = [[1, 2], [2, 1], [2, 3], [4, 3], [4, 1], [1, 4], [2, 3]] edges.each{ |edge| edge.map!{ |e| e - 1 } } graph.add(edges) groups = graph.scc assert_equal 2, groups.size assert_equal [[0, 1, 3], [2]], groups end def test_error graph = SCC.new(2) assert_raises(ArgumentError){ graph.add_edge(0, 2) } end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/crt.rb' class CrtTest < Minitest::Test def test_two_elements [*1 .. 5].repeated_permutation(2){ |a, b| [*-4 .. 4].repeated_permutation(2){ |c, d| rem, mod = crt([c, d], [a, b]) if mod == 0 assert (0 ... a.lcm(b)).none?{ |x| x % a == c && x % b == d } else assert_equal a.lcm(b), mod assert_equal c % a, rem % a assert_equal d % b, rem % b end } } end def test_three_elements [*1 .. 4].repeated_permutation(3){ |a, b, c| [*-4 .. 4].repeated_permutation(3){ |d, e, f| rem, mod = crt([d, e, f], [a, b, c]) lcm = [a, b, c].reduce :lcm if mod == 0 assert (0 ... lcm).none?{ |x| x % a == d && x % b == e && x % c == f } else assert_equal lcm, mod assert_equal d % a, rem % a assert_equal e % b, rem % b assert_equal f % c, rem % c end } } end def test_random_array max_ans = 10**1000 max_num = 10**18 20.times{ ans = rand(max_ans) m = (0 ... 20).map{ rand(1 .. max_num) } r = m.map{ |m| ans % m } mod = m.reduce(:lcm) assert_equal [ans % mod, mod], crt(r, m) } end def test_no_solution assert_equal [0, 0], crt([0, 1], [2, 2]) assert_equal [0, 0], crt([1, 0, 5], [2, 4, 17]) end def test_empty_array assert_equal [0, 1], crt([], []) end def test_argument_error # different size assert_raises(ArgumentError){ crt([], [1]) } assert_raises(ArgumentError){ crt([1], []) } assert_raises(ArgumentError){ crt([*1 .. 10**5], [*1 .. 10**5 - 1]) } assert_raises(ArgumentError){ crt([*1 .. 10**5 - 1], [*1 .. 10**5]) } # modulo 0 assert_raises(ArgumentError){ crt([0], [0]) } assert_raises(ArgumentError){ crt([0] * 5, [2, 3, 5, 7, 0]) } end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/segtree.rb' class SegtreeNaive def initialize(arg, e, &op) case arg when Integer @d = Array.new(arg) { e } end @n = @d.size @e = e @op = proc(&op) end def set(pos, x) @d[pos] = x end def get(pos) @d[pos] end def prod(l, r) res = @e (l ... r).each do |i| res = @op.call(res, @d[i]) end res end def all_prod prod(0, @n) end def max_right(l, &f) sum = @e (l ... @n).each do |i| sum = @op.call(sum, @d[i]) return i unless f.call(sum) end @n end def min_left(r, &f) sum = @e (r - 1).downto(0) do |i| sum = @op.call(@d[i], sum) return i + 1 unless f.call(sum) end 0 end end class SegtreeTest < Minitest::Test INF = (1 << 60) - 1 def test_zero e = '$' op = ->{} # This is unused if Segtree size is 0. s = Segtree.new(0, e, &op) assert_equal e, s.all_prod assert_raises(ArgumentError){ Segtree.new(e, &op) } end def test_one e = '$' op = proc do |a, b| if a == e b elsif b == e a else # a + b # This is unused if Segtree size is 1. end end s = Segtree.new(1, e, &op) assert_equal '$', s.all_prod assert_equal '$', s.get(0) assert_equal '$', s[0] assert_equal '$', s.prod(0, 1) s.set(0, "dummy") assert_equal "dummy", s.get(0) assert_equal e, s.prod(0, 0) assert_equal "dummy", s.prod(0, 1) assert_equal e, s.prod(1, 1) end def test_compare_naive op = proc do |a, b| if a == '$' b elsif b == '$' a else a + b end end (0..20).each do |n| seg0 = SegtreeNaive.new(n, '$', &op) seg1 = Segtree.new(n, '$', &op) assert_equal seg0.all_prod, seg1.all_prod n.times do |i| s = "" s += ("a".ord + i).chr seg0.set(i, s) seg1.set(i, s) end (0...n).each do |i| assert_equal seg0.get(i), seg1.get(i) end 0.upto(n) do |l| l.upto(n) do |r| assert_equal seg0.prod(l, r), seg1.prod(l, r), "prod test failed" end end assert_equal seg0.all_prod, seg1.all_prod y = '' leq_y = proc{ |x| x.size <= y.size } 0.upto(n) do |l| l.upto(n) do |r| y = seg1.prod(l, r) assert_equal seg0.max_right(l, &leq_y), seg1.max_right(l, &leq_y), "max_right test failed" end end 0.upto(n) do |r| 0.upto(r) do |l| y = seg1.prod(l, r) assert_equal seg0.min_left(r, &leq_y), seg1.min_left(r, &leq_y), "min_left test failed" end end end end # https://atcoder.jp/contests/practice2/tasks/practice2_j def test_alpc_max_right a = [1, 2, 3, 2, 1] st = Segtree.new(a, -INF) { |x, y| [x, y].max } assert_equal 3, st.prod(1 - 1, 5) # [0, 5) assert_equal 3, st.max_right(2 - 1) { |v| v < 3 } + 1 st.set(3 - 1, 1) assert_equal 2, st.get(1) assert_equal 2, st.all_prod assert_equal 2, st.prod(2 - 1, 4) # [1, 4) assert_equal 6, st.max_right(1 - 1) { |v| v < 3 } + 1 end # https://atcoder.jp/contests/practice2/tasks/practice2_j def test_alpc_min_left n = 5 a = [1, 2, 3, 2, 1].reverse st = Segtree.new(a, -INF) { |x, y| [x, y].max } assert_equal 3, st.prod(n - 5, n - 1 + 1) # [0, 5) assert_equal 3, n - st.min_left(n - 2 + 1) { |v| v < 3 } + 1 st.set(n - 3, 1) assert_equal 2, st.get(n - 1 - 1) assert_equal 2, st.all_prod assert_equal 2, st.prod(n - 4, n - 2 + 1) # [1, 4) assert_equal 6, n - st.min_left(n - 1 + 1) { |v| v < 3 } + 1 end def test_sum a = (1..10).to_a seg = Segtree.new(a, 0){ |x, y| x + y } assert_equal 1, seg.get(0) assert_equal 10, seg.get(9) assert_equal 55, seg.all_prod assert_equal 55, seg.prod(0, 10) assert_equal 54, seg.prod(1, 10) assert_equal 45, seg.prod(0, 9) assert_equal 10, seg.prod(0, 4) assert_equal 15, seg.prod(3, 6) assert_equal 0, seg.prod(0, 0) assert_equal 0, seg.prod(1, 1) assert_equal 0, seg.prod(2, 2) assert_equal 0, seg.prod(4, 4) seg.set(4, 15) assert_equal 65, seg.all_prod assert_equal 65, seg.prod(0, 10) assert_equal 64, seg.prod(1, 10) assert_equal 55, seg.prod(0, 9) assert_equal 10, seg.prod(0, 4) assert_equal 25, seg.prod(3, 6) assert_equal 0, seg.prod(0, 0) assert_equal 0, seg.prod(1, 1) assert_equal 0, seg.prod(2, 2) assert_equal 0, seg.prod(4, 4) end # [Experimental] def test_experimental_range_prod a = (1..10).to_a seg = Segtree.new(a, 0){ |x, y| x + y } assert_equal 55, seg.prod(0...10) assert_equal 54, seg.prod(1...10) assert_equal 45, seg.prod(0...9) assert_equal 10, seg.prod(0...4) assert_equal 15, seg.prod(3...6) assert_equal 55, seg.prod(0..9) assert_equal 54, seg.prod(1..9) assert_equal 54, seg.prod(1..) assert_equal 54, seg.prod(1...) assert_equal 54, seg.prod(1..-1) assert_equal 45, seg.prod(0..8) assert_equal 45, seg.prod(-10..-2) assert_equal 10, seg.prod(0..3) assert_equal 15, seg.prod(3..5) end def test_max_right a = [*0..6] st = Segtree.new(a, 0){ |x, y| x + y } # [0, 1, 2, 3, 4, 5, 6] i # [0, 1, 3, 6, 10, 15, 21] prod(0, i) # [t, t, t, f, f, f, f] prod(0, i) < 5 assert_equal 3, st.max_right(0){ |x| x < 5 } # [4, 5, 6] i # [4, 9, 15] prod(4, i) # [t, f, f] prod(4, i) >= 4 assert_equal 5, st.max_right(4){ |x| x <= 4 } # [3, 4, 5, 6] i # [3, 7, 12, 18] prod(3, i) # [f, f, f, f] prod(3) <= 2 assert_equal 3, st.max_right(3){ |x| x <= 2 } end def test_min_left a = [1, 2, 3, 2, 1] st = Segtree.new(a, -10**18){ |x, y| [x, y].max } # [0, 1, 2, 3, 4] i # [3, 3, 3, 2, 1] prod(i, 5) # [f, f, f, f, f] prod(i, 5) < 1 assert_equal 5, st.min_left(5){ |v| v < 1 } # [0, 1, 2, 3, 4] i # [3, 3, 3, 2, 1] prod(i, 5) # [f, f, f, f, t] prod(i, 5) < 2 assert_equal 4, st.min_left(5){ |v| v < 2 } # [0, 1, 2, 3, 4] i # [3, 3, 3, 2, 1] prod(i, 5) assert_equal 5, st.min_left(5){ |v| v < 1 } assert_equal 4, st.min_left(5){ |v| v < 2 } assert_equal 3, st.min_left(5){ |v| v < 3 } assert_equal 0, st.min_left(5){ |v| v < 4 } assert_equal 0, st.min_left(5){ |v| v < 5 } # [0, 1, 2, 3] i # [3, 3, 3, 2] prod(i, 4) assert_equal 4, st.min_left(4){ |v| v < 1 } assert_equal 4, st.min_left(4){ |v| v < 2 } assert_equal 3, st.min_left(4){ |v| v < 3 } assert_equal 0, st.min_left(4){ |v| v < 4 } assert_equal 0, st.min_left(4){ |v| v < 5 } end # AtCoder ABC185 F - Range Xor Query # https://atcoder.jp/contests/abc185/tasks/abc185_f def test_xor_abc185f a = [1, 2, 3] st = Segtree.new(a, 0){ |x, y| x ^ y } assert_equal 0, st.prod(1 - 1, 3 - 1 + 1) assert_equal 1, st.prod(2 - 1, 3 - 1 + 1) st.set(2 - 1, st.get(2 - 1) ^ 3) assert_equal 2, st.prod(2 - 1, 3 - 1 + 1) end # AtCoder ABC185 F - Range Xor Query # https://atcoder.jp/contests/abc185/tasks/abc185_f def test_acl_original_argument_order_of_new a = [1, 2, 3] op = ->(x, y){ x ^ y } e = 0 st = Segtree.new(a, op, e) assert_equal 0, st.prod(1 - 1, 3 - 1 + 1) assert_equal 1, st.prod(2 - 1, 3 - 1 + 1) st.set(2 - 1, st.get(2 - 1) ^ 3) assert_equal 2, st.prod(2 - 1, 3 - 1 + 1) end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/priority_queue.rb' class PriorityQueueTest < Minitest::Test def test_max_initialization pq = PriorityQueue.max([5, -9, 8, -4, 0, 2, -1]) assert_equal 8, pq.pop assert_equal 5, pq.pop assert_equal 2, pq.first end def test_min_initialization pq = PriorityQueue.min([5, -9, 8, -4, 0, 2, -1]) assert_equal(-9, pq.pop) assert_equal(-4, pq.pop) end # https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/all/ALDS1_9_C def test_aizu_sample_case q = PriorityQueue.new([2, 7, 8]) assert_equal 8, q.get assert_equal 8, q.pop q.push(19) q.push(10) assert_equal 19, q.pop assert_equal 10, q.pop q.append(8) assert_equal 8, q.pop assert_equal 7, q.pop q.<< 3 q.push(4) q.push(1) assert_equal 4, q.pop assert_equal [3, 2, 1], q.heap assert_equal 3, q.pop assert_equal 2, q.pop assert_equal 1, q.pop assert_equal true, q.empty? assert_nil q.top end def test_asc_order q = HeapQueue.new { |x, y| x < y } q << 2 q << 3 q << 1 assert_match /<PriorityQueue: @heap:\(1, 3, 2\), @comp:<Proc .+:\d+>>/, q.to_s assert_equal 1, q.pop assert_equal 2, q.pop assert_equal 3, q.pop end def test_initialize_without_argument pq = PriorityQueue.new assert_equal 0, pq.size assert_equal true, pq.empty? assert_nil pq.top assert_nil pq.pop assert_match /<PriorityQueue: @heap:\(\), @comp:<Proc .+:\d+>>/, pq.to_s pq << 0 assert_equal 1, pq.size assert_equal false, pq.empty? pq.pop assert_equal 0, pq.size assert_equal true, pq.empty? end def test_syntax_sugar_new pq = PriorityQueue[5, 9, 2] assert_equal 3, pq.size assert_equal 9, pq.top assert_equal 9, pq.pop assert_equal 5, pq.pop assert_equal 2, pq.pop end def test_syntax_sugar_new_with_block pq = PriorityQueue[5, 9, 2] { |x, y| x < y } assert_equal 3, pq.size assert_equal 2, pq.top assert_equal 2, pq.pop assert_equal 5, pq.pop assert_equal 9, pq.pop end def test_serial_push pq = PriorityQueue.new { |x, y| x < y } pq << 2 << 3 << 1 assert_equal 1, pq.pop assert_equal 2, pq.pop assert_equal 3, pq.pop end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
require 'minitest' require 'minitest/autorun' require_relative '../lib/core_ext/integer.rb' class IntegerTest < Minitest::Test def test_divisors assert_equal [1], 1.divisors assert_equal [1, 2], 2.divisors assert_equal [1, 3], 3.divisors assert_equal [1, 2, 4], 4.divisors assert_equal [1, 5], 5.divisors assert_equal [1, 2, 3, 6], 6.divisors assert_equal [1, 7], 7.divisors assert_equal [1, 2, 4, 8], 8.divisors assert_equal [1, 3, 9], 9.divisors assert_equal [1, 2, 5, 10], 10.divisors assert_equal [1, 2, 4, 5, 10, 20, 25, 50, 100], 100.divisors # large prime number assert_equal [1, 2**31 - 1], (2**31 - 1).divisors assert_equal [1, 1_000_000_007], 1_000_000_007.divisors assert_equal [1, 1_000_000_009], 1_000_000_009.divisors assert_equal [1, 67_280_421_310_721], 67_280_421_310_721.divisors # large composite number p1 = 2**13 - 1 p2 = 2**17 - 1 assert_equal [1, p1, p2, p1 * p2], (p1 * p2).divisors assert_raises(ZeroDivisionError){ 0.divisors } assert_equal [-1, 1], -1.divisors assert_equal [-2, -1, 1, 2], -2.divisors assert_equal [-3, -1, 1, 3], -3.divisors assert_equal [-4, -2, -1, 1, 2, 4], -4.divisors assert_equal [-6, -3, -2, -1, 1, 2, 3, 6], -6.divisors end def test_each_divisor d10 = [] 10.each_divisor{ |d| d10 << d } assert_equal [1, 2, 5, 10], d10 assert_equal [1], 1.each_divisor.to_a assert_equal [1, 3], 3.each_divisor.to_a assert_equal [1, 2, 4], 4.each_divisor.to_a assert_equal [1, 2, 3, 6], 6.each_divisor.to_a assert_raises(ZeroDivisionError){ 0.each_divisor.to_a } assert_equal [-1, 1], -1.each_divisor.to_a assert_equal [-2, -1, 1, 2], -2.each_divisor.to_a assert_equal [-4, -2, -1, 1, 2, 4], -4.each_divisor.to_a assert_equal [-6, -3, -2, -1, 1, 2, 3, 6], -6.each_divisor.to_a end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/dsu.rb' class UnionFindTest < Minitest::Test def test_zero uf = DSU.new(0) assert_equal [], uf.groups end def test_empty uf = DSU.new assert_equal [], uf.groups end def test_simple uf = DSU.new(2) x = uf.merge(0, 1) assert_equal x, uf.leader(0) assert_equal x, uf.leader(1) assert x, uf.same?(0, 1) assert_equal 2, uf.size(0) end def test_line n = 30 uf = DSU.new(n) (n - 1).times { |i| uf.merge(i, i + 1) } assert_equal n, uf.size(0) assert_equal 1, uf.groups.size end def test_line_reverse n = 30 uf = DSU.new(n) (n - 2).downto(0) { |i| uf.merge(i, i + 1) } assert_equal n, uf.size(0) assert_equal 1, uf.groups.size end def test_groups d = DSU.new(4) groups = d.groups.map(&:sort).sort assert_equal 4, groups.size assert_equal [[0], [1], [2], [3]], groups d.merge(0, 1) d.merge(2, 3) groups = d.groups.map(&:sort).sort assert_equal 2, groups.size assert_equal [0, 1], groups[0] assert_equal [2, 3], groups[1] d.merge(0, 2) groups = d.groups.map(&:sort).sort assert_equal 1, groups.size, "[PR #64]" assert_equal [0, 1, 2, 3], groups[0], "[PR #64]" end def test_atcoder_typical_true uft = UnionFind.new(8) query = [[0, 1, 2], [0, 3, 2], [1, 1, 3], [0, 2, 4], [1, 4, 1], [0, 4, 2], [0, 0, 0], [1, 0, 0]] query.each do |(q, a, b)| if q == 0 uft.unite(a, b) else assert uft.same?(a, b) end end end def test_aizu_sample_true uft = UnionFind.new(5) query = [[0, 1, 4], [0, 2, 3], [1, 1, 4], [1, 3, 2], [0, 1, 3], [1, 2, 4], [0, 0, 4], [1, 0, 2], [1, 3, 0]] query.each do |(q, a, b)| if q == 0 uft.unite(a, b) else assert uft.same?(a, b) end end end def test_aizu_sample_false uft = UnionFind.new(5) query = [[0, 1, 4], [0, 2, 3], [1, 1, 2], [1, 3, 4], [0, 1, 3], [1, 3, 0], [0, 0, 4]] query.each do |(q, a, b)| if q == 0 uft.unite(a, b) else assert !uft.same?(a, b) end end end def test_rand_isoration n = 30 uft = UnionFind.new(n) values = [0, 1, 2, 3, 5, 10] values.product(values) do |a, b| if a == b assert uft.same?(a, b) else assert !uft.same?(a, b) end end assert_equal Array.new(n){ |i| [i] }, uft.groups end def test_merge uft = UnionFind.new(2) assert_equal 0, uft.merge(0, 1) end def test_root_with_dynamic_expansion uft = UnionFind.new assert_equal false, uft[0] == uft[1] uft.unite(0, 1) assert_equal true, uft[0] == uft[1] end def test_edge_cases_error assert_raises(ArgumentError){ UnionFind.new(-1) } n = 2 uft = UnionFind.new(n) uft.unite(0, n - 1) assert uft.same?(0, n - 1) assert_equal 0, uft.leader(0) assert_equal 2, uft.size(0) assert_raises(ArgumentError){ uft.merge(1, n) } assert_raises(ArgumentError){ uft.merge(n, 1) } assert_raises(ArgumentError){ uft.same?(1, n) } assert_raises(ArgumentError){ uft.same?(n, 1) } assert_raises(ArgumentError){ uft.leader(n) } assert_raises(ArgumentError){ uft.size(n) } end def test_to_s uft = UnionFind.new(2) assert_equal "<DSU: @n=2, [-1, -1]>", uft.to_s end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require 'openssl' require_relative '../lib/modint.rb' # test ModInt class ModIntTest < Minitest::Test def setup @mods = [1, 2, 3, 6, 10, 11, 1_000_000_007] @primes = [2, 3, 5, 7, 1_000_000_007] @values = [-100_000, -2, -1, 0, 1, 2, 10_000_000_000] end def test_example ModInt.set_mod(11) # equals `ModInt.mod = 11` assert_equal 11, ModInt.mod a = ModInt(10) b = 3.to_m assert_equal 8, -b # 8 mod 11 assert_equal 2, a + b # 2 mod 11 assert_equal 0, 1 + a # 0 mod 11 assert_equal 7, a - b # 7 mod 11 assert_equal 4, b - a # 4 mod 11 assert_equal 8, a * b # 8 mod 11 assert_equal 4, b.inv # 4 mod 11 assert_equal 7, a / b # 7 mod 11 a += b assert_equal 2, a # 2 mod 11 a -= b assert_equal 10, a # 10 mod 11 a *= b assert_equal 8, a # 8 mod 11 a /= b assert_equal 10, a # 10 mod 11 assert_equal 5, ModInt(2)**4 # 5 mod 11 assert_equal 5, ModInt(2).pow(4) # 5 mod 11 assert_output("10\n") { puts a } # 10 assert_output("10 mod 11\n") { p a } # 10 mod 11 assert_equal 3, ModInt.raw(3) # 3 mod 11 end def test_method_zero? ModInt.mod = 11 assert_equal 11, ModInt.mod assert_equal true, ModInt.new(11).zero? assert_equal true, ModInt.new(-11).zero? assert_equal true, ModInt.new(0).zero? assert_equal false, ModInt.new(12).zero? assert_equal false, ModInt.new(1).zero? assert_equal false, ModInt.new(-1).zero? end def test_pred ModInt.mod = 11 assert_equal 11, ModInt.mod m = ModInt.new(12) assert_equal 2, m.succ assert_equal 0, m.pred assert_equal 1, m end def test_usage ModInt.mod = 11 assert_equal 11, ModInt.mod assert_equal 4, ModInt.new(4) assert_equal 7, -ModInt.new(4) assert_equal 4, ModInt.new(4).to_i assert_equal 7, (-ModInt.new(4)).to_i assert ModInt.new(1) != ModInt.new(4) assert ModInt.new(1) == ModInt.new(12) ModInt.mod = 998_244_353 assert_equal 998_244_353, ModInt.mod assert_equal 3, (ModInt(1) + ModInt(2)) assert_equal 3, (1 + ModInt(2)) assert_equal 3, (ModInt(1) + 2) assert_equal 3, ModInt.mod = 3 assert_equal 3, ModInt.mod assert_equal 1, ModInt(2) - ModInt(1) assert_equal 0, ModInt(1) + ModInt(2) assert_equal 0, 1 + ModInt(2) assert_equal 0, ModInt(1) + 2 ModInt.set_mod(11) assert_equal 11, ModInt.mod assert_equal 4, ModInt(3) * ModInt(5) assert_equal 4, ModInt.new(4) assert_equal 7, -ModInt.new(4) end def test_self_prime? assert_equal false, ModInt.prime?(1) assert_equal true, ModInt.prime?(2) assert_equal true, ModInt.prime?(3) assert_equal false, ModInt.prime?(4) assert_equal true, ModInt.prime?(5) assert_equal false, ModInt.prime?(6) assert_equal true, ModInt.prime?(7) assert_equal false, ModInt.prime?(8) assert_equal false, ModInt.prime?(9) assert_equal false, ModInt.prime?(10) assert_equal true, ModInt.prime?(11) assert_equal true, ModInt.prime?(10**9 + 7) end def test_add @mods.each do |mod| ModInt.mod = mod @values.product(@values) do |(x, y)| expected = (x + y) % mod assert_equal expected, x.to_m + y assert_equal expected, x + y.to_m assert_equal expected, x.to_m + y.to_m end end end def test_sub @mods.each do |mod| ModInt.mod = mod @values.product(@values) do |(x, y)| expected = (x - y) % mod assert_equal expected, x.to_m - y assert_equal expected, x - y.to_m assert_equal expected, x.to_m - y.to_m end end end def test_mul @mods.each do |mod| ModInt.mod = mod @values.product(@values) do |(x, y)| expected = (x * y) % mod assert_equal expected, x.to_m * y assert_equal expected, x * y.to_m assert_equal expected, x.to_m * y.to_m end end end def test_equal @mods.each do |mod| ModInt.mod = mod @values.each do |value| assert_equal true, (value % mod) == value.to_m assert_equal true, value.to_m == (value % mod) assert_equal true, value.to_m == value.to_m end end end def test_not_equal @mods.each do |mod| ModInt.mod = mod @values.each do |value| assert_equal false, (value % mod) != value.to_m assert_equal false, value.to_m != (value % mod) assert_equal false, value.to_m != value.to_m end end end def test_pow xs = [-6, -2, -1, 0, 1, 2, 6, 100] ys = [0, 1, 2, 3, 6, 100] @mods.each do |mod| ModInt.mod = mod xs.product(ys) do |(x, y)| expected = (x**y) % mod assert_equal expected, x.to_m**y assert_equal expected, x.to_m.pow(y) end end end def test_pow_method mods = [2, 3, 10, 1_000_000_007] xs = [-6, -2, -1, 0, 1, 2, 1_000_000_007] ys = [0, 1, 2, 1_000_000_000] mods.each do |mod| ModInt.mod = mod xs.product(ys) do |(x, y)| expected = x.pow(y, mod) assert_equal expected, x.to_m**y assert_equal expected, x.to_m.pow(y) end end end def test_pow_in_the_case_mod_is_one # Ruby 2.7.1 may have a bug: i.pow(0, 1) #=> 1 if i is a Integer # this returns should be 0 ModInt.mod = 1 assert_equal 0, ModInt(-1).pow(0), "corner case when modulo is one" assert_equal 0, ModInt(0).pow(0), "corner case when modulo is one" assert_equal 0, ModInt(1).pow(0), "corner case when modulo is one" assert_equal 0, ModInt(-5)**0, "corner case when modulo is one" assert_equal 0, ModInt(0)**0, "corner case when modulo is one" assert_equal 0, ModInt(5)**0, "corner case when modulo is one" end def test_inv_in_the_case_that_mod_is_prime @primes.each do |prime_mod| ModInt.mod = prime_mod @values.each do |value| next if (value % prime_mod).zero? expected = value.to_bn.mod_inverse(prime_mod).to_i assert_equal expected, value.to_m.inv assert_equal expected, 1 / value.to_m assert_equal expected, 1.to_m / value assert_equal expected, 1.to_m / value.to_m end end end def test_inv_in_the_random_mod_case mods = [2, 3, 4, 5, 10, 1_000_000_007] mods.each do |mod| ModInt.mod = mod assert_equal 1, 1.to_m.inv assert_equal 1, 1 / 1.to_m assert_equal 1, 1.to_m / 1 assert_equal mod - 1, (mod - 1).to_m.inv assert_equal mod - 1, 1 / (mod - 1).to_m assert_equal mod - 1, 1.to_m / (mod - 1) assert_equal mod - 1, 1.to_m / (mod - 1).to_m end end def test_div_in_the_case_that_mod_is_prime @primes.each do |prime_mod| ModInt.mod = prime_mod @values.product(@values) do |(x, y)| next if (y % prime_mod).zero? expected = (x * y.to_bn.mod_inverse(prime_mod).to_i) % prime_mod assert_equal expected, x.to_m / y assert_equal expected, x / y.to_m assert_equal expected, x.to_m / y.to_m end end end def test_inv_in_the_case_that_mod_is_not_prime mods = { 4 => [1, 3], 6 => [1, 5], 9 => [2, 4, 7, 8], 10 => [3, 7, 9] } mods.each do |(mod, numbers)| ModInt.mod = mod @values.product(numbers) do |(x, y)| expected = (x * y.to_bn.mod_inverse(mod).to_i) % mod assert_equal expected, x.to_m / y assert_equal expected, x / y.to_m assert_equal expected, x.to_m / y.to_m end end end def test_inc! ModInt.set_mod(11) m = ModInt(20) assert_equal 9, m assert_equal 10, m.inc! assert_equal 10, m assert_equal 0, m.inc! assert_equal 0, m end def test_dec! ModInt.set_mod(11) m = ModInt(12) assert_equal 1, m assert_equal 0, m.dec! assert_equal 0, m assert_equal 10, m.dec! assert_equal 10, m end def test_unary_operator_plus ModInt.set_mod(11) m = ModInt(12) assert m.equal?(+m) end def test_to_i @mods.each do |mod| ModInt.mod = mod @values.each do |value| expected = value % mod actual = value.to_m.to_i assert actual.is_a?(Integer) assert_equal expected, actual end end end def test_to_int @mods.each do |mod| ModInt.mod = mod @values.each do |value| expected = value % mod actual = value.to_m.to_int assert actual.is_a?(Integer) assert_equal expected, actual end end end def test_zero? @mods.each do |mod| ModInt.mod = mod @values.each do |value| expected = (value % mod).zero? actual = value.to_m.zero? assert_equal expected, actual end end end def test_integer_to_modint ModInt.mod = 10**9 + 7 @values.each do |value| expected = ModInt(value) assert_equal expected, value.to_m assert_equal expected, value.to_modint end end def test_string_to_modint ModInt.mod = 10**9 + 7 values = ['-100', '-1', '-2', '0', '1', '2', '10', '123', '100000000000000', '1000000007'] values.concat(values.map { |str| "#{str}\n" }) values.each do |value| expected = ModInt(value.to_i) assert_equal expected, value.to_m assert_equal expected, value.to_modint end end def test_output_by_p_method ModInt.mod = 10**9 + 7 assert_output("1000000006 mod 1000000007\n") { p(-1.to_m) } assert_output("1000000006 mod 1000000007\n") { p (10**9 + 6).to_m } assert_output("0 mod 1000000007\n") { p (10**9 + 7).to_m } assert_output("1 mod 1000000007\n") { p (10**9 + 8).to_m } @mods.each do |mod| ModInt.mod = mod @values.each do |n| expected = "#{n % mod} mod #{mod}\n" assert_output(expected) { p n.to_m } end end end def test_output_by_puts_method ModInt.mod = 10**9 + 7 assert_output("1000000006\n") { puts(-1.to_m) } assert_output("1000000006\n") { puts (10**9 + 6).to_m } assert_output("0\n") { puts (10**9 + 7).to_m } assert_output("1\n") { puts (10**9 + 8).to_m } @mods.each do |mod| ModInt.mod = mod @values.each do |n| expected = "#{n % mod}\n" assert_output(expected) { puts n.to_m } end end end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/z_algorithm.rb' def z_algorithm_naive(s) n = s.size return (0 ... n).map{ |i| j = 0 j += 1 while i + j < n && s[j] == s[i + j] j } end class ZAlgorithmTest < Minitest::Test def test_random_string 20.times{ s = (0 ... 20).map{ rand(' '.ord .. '~'.ord).chr }.join assert_equal z_algorithm_naive(s), z_algorithm(s) } end def test_random_array_of_small_integer max_num = 5 20.times{ a = (0 ... 20).map{ rand(-max_num .. max_num) } assert_equal z_algorithm_naive(a), z_algorithm(a) } end def test_random_array_of_large_integer max_num = 10**18 20.times{ a = (0 ... 20).map{ rand(-max_num .. max_num) } assert_equal z_algorithm_naive(a), z_algorithm(a) } end def test_random_array_of_char 20.times{ a = (0 ... 20).map{ rand(' '.ord .. '~'.ord).chr } assert_equal z_algorithm_naive(a), z_algorithm(a) } end def test_random_array_of_array candidate = [[], [0], [1], [2], [0, 0], [1, 1], [2, 2]] 20.times{ a = (0 ... 20).map{ candidate.sample.dup } assert_equal z_algorithm_naive(a), z_algorithm(a) } end def test_repeated_string max_n = 30 20.times{ n = rand(1..max_n) s = 'A' * n assert_equal [*1 .. n].reverse, z_algorithm(s) } end def test_unique_array max_num = 10**18 20.times{ a = (0 ... 20).map{ rand(-max_num .. max_num) }.uniq n = a.size # [n, 0, 0, ..., 0] assert_equal [n] + [0] * (n - 1), z_algorithm(a) } end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/lazy_segtree.rb' # Test for Segment tree with lazy propagation class LazySegtreeTest < Minitest::Test # AOJ: RSQ and RAQ # https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_F def test_aizu_dsl_2_f inf = 2**31 - 1 e = inf id = inf op = proc { |x, y| [x, y].min } mapping = proc { |f, x| f == id ? x : f } composition = proc { |f, g| f == id ? g : f } n = 3 seg = LazySegtree.new(n, e, id, op, mapping, composition) seg.range_apply(0, 1 + 1, 1) seg.range_apply(1, 2 + 1, 3) seg.range_apply(2, 2 + 1, 2) seg.prod(0, 2 + 1) assert_equal 1, seg.prod(0, 2 + 1) assert_equal 2, seg.prod(1, 2 + 1) n = 1 seg = LazySegtree.new(n, e, id, op, mapping, composition) assert_equal 2_147_483_647, seg.prod(0, 0 + 1) seg.range_apply(0, 0 + 1, 5) assert_equal 5, seg.prod(0, 0 + 1) end # AOJ: RMQ and RUQ # https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_G def test_aizu_dsl_2_g e = [0, 1] id = 0 op = proc{ |(vx, sx), (vy, sy)| [vx + vy, sx + sy] } mapping = proc{ |f, (s, sz)| [s + f * sz, sz] } composition = proc{ |f, g| f + g } n = 3 seg = LazySegtree.new(n, e, id, op, mapping, composition) seg.range_apply(0, 2, 1) seg.range_apply(1, 3, 2) seg.range_apply(2, 3, 3) assert_equal 4, seg.prod(0, 2)[0] assert_equal 8, seg.prod(1, 3)[0] n = 4 seg = LazySegtree.new(n, e, id, op, mapping, composition) assert_equal 0, seg.prod(0, 4)[0] seg.range_apply(0, 4, 1) assert_equal 4, seg.prod(0, 4)[0] end # AOJ: RMQ and RAQ # https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_H def test_aizu_dsl_2_h vector = [0] * 6 e = 1_000_000_000 id = 0 seg = LazySegtree.new(vector, e, id){ |x, y| [x, y].min } seg.set_mapping{ |f, x| f + x } seg.set_composition{ |f, g| f + g } seg.range_apply(1, 3 + 1, 1) seg.range_apply(2, 4 + 1, -2) assert_equal -2, seg.prod(0, 5 + 1) assert_equal 0, seg.prod(0, 1 + 1) seg.range_apply(3, 5 + 1, 3) assert_equal 1, seg.prod(3, 4 + 1) assert_equal -1, seg.prod(0, 5 + 1) end # AOJ: RSQ and RUQ # https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_I def test_aizu_dsl_2_i vector = Array.new(6){ [0, 1] } e = [0, 0] id = 10**18 seg = LazySegtree.new(vector, e, id){ |(vx, sx), (vy, sy)| [vx + vy, sx + sy] } seg.set_mapping{ |f, x| x[0] = f * x[1] unless f == id; x } seg.set_composition{ |f, g| f == id ? g : f } seg.range_apply(1, 3 + 1, 1) seg.range_apply(2, 4 + 1, -2) assert_equal [-5, 6], seg.prod(0, 5 + 1) assert_equal [1, 2], seg.prod(0, 1 + 1) seg.range_apply(3, 5 + 1, 3) assert_equal [6, 2], seg.prod(3, 4 + 1) assert_equal [8, 6], seg.prod(0, 5 + 1) end def test_usage vector = [0] * 10 e = -1_000_000_000 id = 0 op = proc { |x, y| [x, y].max } mapping = proc { |f, x| f + x } composition = proc { |f, g| f + g } seg = LazySegtree.new(vector, e, id, op, mapping, composition) assert_equal 0, seg.all_prod seg.range_apply(0, 3, 5) assert_equal 5, seg.all_prod seg.apply(2, -10) assert_equal -5, seg.prod(2, 3) assert_equal 0, seg.prod(2, 4) end def test_proc_setter vector = [0] * 10 e = -1_000_000_000 id = 0 seg = LazySegtree.new(vector, e, id){ |x, y| [x, y].max } seg.set_mapping{ |f, x| f + x } seg.set_composition{ |f, g| f + g } assert_equal 0, seg.all_prod seg.range_apply(0, 3, 5) assert_equal 5, seg.all_prod seg.apply(2, -10) assert_equal -5, seg.prod(2, 3) assert_equal 0, seg.prod(2, 4) end def test_empty_lazy_segtree vector = [] e = -1_000_000_000 id = 0 empty_seg = LazySegtree.new(vector, e, id){ |x, y| [x, y].max } empty_seg.set_mapping{ |f, x| f + x } empty_seg.set_composition{ |f, g| f + g } assert_equal e, empty_seg.all_prod end def test_one_lazy_segtree vector = [0] e = -1_000_000_000 id = 0 seg = LazySegtree.new(vector, e, id){ |x, y| [x, y].max } seg.set_mapping{ |f, x| f + x } seg.set_composition{ |f, g| f + g } assert_equal e, seg.prod(0, 0) assert_equal e, seg.prod(1, 1) assert_equal 0, seg.prod(0, 1) assert_equal 0, seg.get(0) assert_equal 0, seg[0] end def test_quora2021_skyscraper a = [4, 2, 3, 2, 4, 7, 6, 5] e = -(10**18) id = 10**18 seg = LazySegtree.new(a, e, id){ |x, y| [x, y].max } seg.set_mapping{ |f, x| f == id ? x : f } seg.set_composition{ |f, g| f == id ? g : f } g = proc{ |x| x <= $h } i = 3 - 1 $h = seg.get(i) r = seg.max_right(i, &g) l = seg.min_left(i, &g) assert_equal 3, r - l i = 2 - 1 $h = seg.get(i) r = seg.max_right(i, &g) l = seg.min_left(i, &g) assert_equal 1, r - l seg.set(3 - 1, 8) i = 5 - 1 $h = seg.get(i) r = seg.max_right(i, &g) l = seg.min_left(i, &g) assert_equal 2, r - l seg.range_apply(5 - 1, 7 - 1 + 1, 1) i = 8 - 1 $h = seg.get(i) r = seg.max_right(i, &g) l = seg.min_left(i, &g) assert_equal 5, r - l end def test_min_left vector = [1, 2, 3, 2, 1] e = -1_000_000_000 id = 0 seg = LazySegtree.new(vector, e, id){ |x, y| [x, y].max } seg.set_mapping{ |f, x| f + x } seg.set_composition{ |f, g| f + g } # [0, 1, 2, 3, 4] i # [3, 3, 3, 2, 1] prod(i, 5) assert_equal 5, seg.min_left(5){ |v| v < 1 } assert_equal 4, seg.min_left(5){ |v| v < 2 } assert_equal 3, seg.min_left(5){ |v| v < 3 } assert_equal 0, seg.min_left(5){ |v| v < 4 } assert_equal 0, seg.min_left(5){ |v| v < 5 } end # AOJ: RMQ and RAQ # https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_H def test_apply_3arguments vector = [0] * 6 e = 1_000_000_000 id = 0 seg = LazySegtree.new(vector, e, id){ |x, y| [x, y].min } seg.set_mapping{ |f, x| f + x } seg.set_composition{ |f, g| f + g } seg.apply(1, 3 + 1, 1) seg.apply(2, 4 + 1, -2) assert_equal -2, seg.prod(0, 5 + 1) assert_equal 0, seg.prod(0, 1 + 1) seg.apply(3, 5 + 1, 3) assert_equal 1, seg.prod(3, 4 + 1) assert_equal -1, seg.prod(0, 5 + 1) end # AOJ: RMQ and RUQ # https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_G def test_acl_original_order_new1 op = proc { |(vx, sx), (vy, sy)| [vx + vy, sx + sy] } e = [0, 1] mapping = proc{ |f, (s, sz)| [s + f * sz, sz] } composition = proc{ |f, g| f + g } id = 0 n = 3 seg = LazySegtree.new(n, op, e, mapping, composition, id) seg.apply(0, 2, 1) seg.apply(1, 3, 2) seg.apply(2, 3, 3) assert_equal 4, seg.prod(0, 2)[0] assert_equal 8, seg.prod(1, 3)[0] n = 4 seg = LazySegtree.new(n, op, e, mapping, composition, id) assert_equal 0, seg.prod(0, 4)[0] seg.apply(0, 4, 1) assert_equal 4, seg.prod(0, 4)[0] end # AOJ: RMQ and RAQ # https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_H def test_acl_original_order_new2 vector = [0] * 6 op = ->(x, y){ [x, y].min } e = 1_000_000_000 mapping = ->(f, x){ f + x } composition = ->(f, g) { f + g } id = 0 seg = LazySegtree.new(vector, op, e, mapping, composition, id) seg.range_apply(1, 3 + 1, 1) seg.range_apply(2, 4 + 1, -2) assert_equal -2, seg.prod(0, 5 + 1) assert_equal 0, seg.prod(0, 1 + 1) seg.range_apply(3, 5 + 1, 3) assert_equal 1, seg.prod(3, 4 + 1) assert_equal -1, seg.prod(0, 5 + 1) end # [Experimental] def test_range_prod vector = [0] * 6 op = ->(x, y){ [x, y].min } e = 1_000_000_000 mapping = ->(f, x){ f + x } composition = ->(f, g) { f + g } id = 0 seg = LazySegtree.new(vector, op, e, mapping, composition, id) seg.apply(1..3, 1) seg.apply(2..4, -2) assert_equal -2, seg.prod(0..5) assert_equal -2, seg.prod(0...6) assert_equal -2, seg.prod(0..-1) assert_equal -2, seg.prod(0..) assert_equal -2, seg.prod(0...) assert_equal 0, seg.prod(0..1) assert_equal 0, seg.prod(0...2) seg.apply(3..5, 3) assert_equal 1, seg.prod(3..4) assert_equal -1, seg.prod(0..5) assert_equal -1, seg.prod(0...6) seg.apply(0.., 10) assert_equal 11, seg.prod(3..4) assert_equal 9, seg.prod(0..5) assert_equal 9, seg.prod(0...6) end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/suffix_array.rb' def suffix_array_naive(s) s = s.bytes if s.is_a?(String) n = s.size return (0 ... n).sort_by{ |i| s[i..-1] } end class SuffixArrayTest < Minitest::Test def test_random_array_small_elements max_num = 5 20.times{ a = (0 ... 20).map{ rand(-max_num .. max_num) } assert_equal suffix_array_naive(a), suffix_array(a) } end def test_random_array_big_elements max_num = 10**18 20.times{ a = (0 ... 20).map{ rand(-max_num .. max_num) } assert_equal suffix_array_naive(a), suffix_array(a) } end def test_random_array_given_upper max_num = 100 20.times{ a = (0 ... 20).map{ rand(0 .. max_num) } assert_equal suffix_array_naive(a), suffix_array(a, max_num) } end def test_random_array_calculated_upper max_num = 100 20.times{ a = (0 ... 20).map{ rand(0 .. max_num) } assert_equal suffix_array_naive(a), suffix_array(a, a.max) } end def test_wrong_given_upper assert_raises(ArgumentError){ suffix_array([*0 .. 1_000_000], 999_999) } end def test_random_string 20.times{ s = (0 ... 20).map{ rand(' '.ord .. '~'.ord).chr }.join assert_equal suffix_array_naive(s), suffix_array(s) } end def test_mississippi assert_equal [10, 7, 4, 1, 0, 9, 8, 6, 3, 5, 2], suffix_array("mississippi") end def test_abracadabra assert_equal [10, 7, 0, 3, 5, 8, 1, 4, 6, 9, 2], suffix_array("abracadabra") end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/convolution.rb' def convolution_naive(a, b, mod) n = a.size m = b.size c = [0] * (n + m - 1) n.times{ |i| m.times{ |j| c[i + j] += a[i] * b[j] } } return c.map{ |c| c % mod } end class ConvolutionTest < Minitest::Test def test_for_small_array conv = Convolution.new assert_equal [1], conv.convolution([1], [1]) assert_equal [1, 2], conv.convolution([1], [1, 2]) assert_equal [1, 2], conv.convolution([1, 2], [1]) assert_equal [1, 4, 4], conv.convolution([1, 2], [1, 2]) end def test_random_array_modulo_default max_num = 10**18 conv = Convolution.new 20.times{ a = (0 .. 20).map{ rand(-max_num .. max_num) } b = (0 .. 20).map{ rand(-max_num .. max_num) } assert_equal convolution_naive(a, b, 998_244_353), conv.convolution(a, b) } end def test_random_array_modulo_NTT_friendly_given_proot max_num = 10**18 [[ 998_244_353, 5], # [mod, primitive_root] [ 998_244_353, 100_000_005], [ 998_244_353, 998_244_350], [1_012_924_417, 5], [1_012_924_417, 1_012_924_412], [ 924_844_033, 5], [ 924_844_033, 924_844_028]].each{ |mod, proot| conv = Convolution.new(mod, proot) 20.times{ a = (0 ... 20).map{ rand(-max_num .. max_num) } b = (0 ... 20).map{ rand(-max_num .. max_num) } assert_equal convolution_naive(a, b, mod), conv.convolution(a, b) } } end def test_random_array_modulo_NTT_friendly_not_given_proot max_num = 10**18 [998_244_353, 1_012_924_417, 924_844_033].each{ |mod| conv = Convolution.new(mod) 20.times{ a = (0 ... 20).map{ rand(-max_num .. max_num) } b = (0 ... 20).map{ rand(-max_num .. max_num) } assert_equal convolution_naive(a, b, mod), conv.convolution(a, b) } } end def test_random_array_small_modulo_limit_length max_num = 10**18 [641, 769].each{ |mod| conv = Convolution.new(mod) limlen = 1 limlen *= 2 while (mod - 1) % limlen == 0 limlen /= 2 20.times{ len_a = rand(limlen) + 1 len_b = limlen - len_a + 1 # len_a + len_b - 1 == limlen a = (0 ... len_a).map{ rand(-max_num .. max_num) } b = (0 ... len_b).map{ rand(-max_num .. max_num) } assert_equal convolution_naive(a, b, mod), conv.convolution(a, b) } } end def test_small_modulo_over_limit_length [641, 769].each{ |mod| conv = Convolution.new(mod) limlen = 1 limlen *= 2 while (mod - 1) % limlen == 0 limlen /= 2 # a.size + b.size - 1 == limlen + 1 > limlen assert_raises(ArgumentError){ conv.convolution([*0 ... limlen], [0, 0]) } assert_raises(ArgumentError){ conv.convolution([0, 0], [*0 ... limlen]) } assert_raises(ArgumentError){ conv.convolution([*0 .. limlen / 2], [*0 .. limlen / 2]) } } end def test_empty_array conv = Convolution.new assert_equal [], conv.convolution([], []) assert_equal [], conv.convolution([], [*0 ... 2**19]) assert_equal [], conv.convolution([*0 ... 2**19], []) end def test_calc_primitive_root conv = Convolution.new require 'prime' test_primes = [2] test_primes += Prime.each(10**4).to_a.sample(30) test_primes.each{ |prime| # call private method # ref : https://qiita.com/koshilife/items/ba3a9f7a3ebe85503e4a g = conv.send(:calc_primitive_root, prime) r = 1 assert (1 .. prime - 2).all?{ r = r * g % prime r != 1 } } end end # [EXPERIMENTAL] class ConvolutionMethodTest < Minitest::Test def test_typical_contest assert_equal [5, 16, 34, 60, 70, 70, 59, 36], convolution([1, 2, 3, 4], [5, 6, 7, 8, 9]) assert_equal [871_938_225], convolution([10_000_000], [10_000_000]) end def test_for_small_array assert_equal [1], convolution([1], [1]) assert_equal [1, 2], convolution([1], [1, 2]) assert_equal [1, 2], convolution([1, 2], [1]) assert_equal [1, 4, 4], convolution([1, 2], [1, 2]) end def test_random_array_modulo_default max_num = 10**18 20.times{ a = (0 .. 20).map{ rand(0 .. max_num) } b = (0 .. 20).map{ rand(0.. max_num) } assert_equal convolution_naive(a, b, 998_244_353), convolution(a, b) } end def test_random_array_modulo_NTT_friendly_given_proot max_num = 10**18 [[ 998_244_353, 5], # [mod, primitive_root] [ 998_244_353, 100_000_005], [ 998_244_353, 998_244_350], [1_012_924_417, 5], [1_012_924_417, 1_012_924_412], [ 924_844_033, 5], [ 924_844_033, 924_844_028]].each{ |mod, _proot| 20.times{ a = (0 ... 20).map{ rand(0 .. max_num) } b = (0 ... 20).map{ rand(0 .. max_num) } assert_equal convolution_naive(a, b, mod), convolution(a, b, mod: mod) } } end def test_random_array_modulo_NTT_friendly_not_given_proot max_num = 10**18 [998_244_353, 1_012_924_417, 924_844_033].each{ |mod| 20.times{ a = (0 ... 20).map{ rand(0 .. max_num) } b = (0 ... 20).map{ rand(0 .. max_num) } assert_equal convolution_naive(a, b, mod), convolution(a, b, mod: mod) } } end def test_random_array_small_modulo_limit_length max_num = 10**18 [641, 769].each{ |mod| limlen = 1 limlen *= 2 while (mod - 1) % limlen == 0 limlen /= 2 20.times{ len_a = rand(limlen) + 1 len_b = limlen - len_a + 1 # len_a + len_b - 1 == limlen a = (0 ... len_a).map{ rand(0 .. max_num) } b = (0 ... len_b).map{ rand(0 .. max_num) } assert_equal convolution_naive(a, b, mod), convolution(a, b, mod: mod) } } end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require 'minitest' require 'minitest/autorun' require_relative '../lib/inv_mod.rb' class InvModTest < Minitest::Test def test_prime_mod assert_equal 1, inv_mod(1, 11) assert_equal 6, inv_mod(2, 11) assert_equal 4, inv_mod(3, 11) assert_equal 3, inv_mod(4, 11) assert_equal 9, inv_mod(5, 11) assert_equal 2, inv_mod(6, 11) assert_equal 8, inv_mod(7, 11) assert_equal 7, inv_mod(8, 11) assert_equal 5, inv_mod(9, 11) assert_equal 10, inv_mod(10, 11) assert_equal 1, inv_mod(12, 11) assert_equal 6, inv_mod(13, 11) (1 .. 10).each do |i| assert_equal i.pow(11 - 2, 11), inv_mod(i, 11) end end def test_not_prime_mod assert_equal 1, inv_mod(1, 10) assert_equal 7, inv_mod(3, 10) assert_equal 3, inv_mod(7, 10) assert_equal 9, inv_mod(9, 10) assert_equal 1, inv_mod(11, 10) assert_equal 7, inv_mod(13, 10) assert_equal 3, inv_mod(17, 10) assert_equal 9, inv_mod(19, 10) end def test_inv_hand min_ll = -2**63 max_ll = 2**63 - 1 assert_equal inv_mod(-1, max_ll), inv_mod(min_ll, max_ll) assert_equal 1, inv_mod(max_ll, max_ll - 1) assert_equal max_ll - 1, inv_mod(max_ll - 1, max_ll) assert_equal 2, inv_mod(max_ll / 2 + 1, max_ll) end def test_inv_mod (-10 .. 10).each do |a| (1 .. 30).each do |b| next unless 1 == (a % b).gcd(b) c = inv_mod(a, b) assert 0 <= c assert c < b assert_equal 1 % b, (a * c) % b end end end def test_inv_mod_zero assert_equal 0, inv_mod(0, 1) 10.times do |i| assert_equal 0, inv_mod(i, 1) assert_equal 0, inv_mod(-i, 1) end end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require_relative '../../lib/suffix_array.rb' require_relative '../../lib/lcp_array.rb' s = gets.chomp lcp = lcp_array(s, suffix_array(s)) ans = s.size * (s.size + 1) / 2 lcp.each{ |lcp| ans -= lcp } puts ans
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require_relative '../../lib/fenwick_tree.rb' _, q = gets.split.map(&:to_i) a = gets.split.map(&:to_i) ft = FenwickTree.new(a) q.times do t, u, v = gets.split.map(&:to_i) if t == 0 ft.add(u, v) else puts ft.sum(u, v) end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require_relative '../../lib/priority_queue.rb' # Warning: This sample is a solution of the following problem: # https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_9_C q = PriorityQueue.new ans = [] loop do input = gets.chomp case input when 'end' break when 'extract' ans << q.pop else v = input.split[1].to_i q.push(v) end end puts ans
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true # TLE, but if you replace all @mod with 998244353 and define all method in top level, you may be able to get AC. # https://atcoder.jp/contests/practice2/submissions/16655600 require_relative '../../lib/convolution.rb' _, a, b = $<.map{ |e| e.split.map(&:to_i) } conv = Convolution.new puts conv.convolution(a, b).join("\s")
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require_relative '../../lib/modint.rb' ModInt.set_mod(11) ModInt.mod # 11 a = ModInt(10) b = 3.to_m -b # 8 mod 11 a + b # 2 mod 11 1 + a # 0 mod 11 a - b # 7 mod 11 b - a # 4 mod 11 a * b # 8 mod 11 b.inv # 4 mod 11 a / b # 7 mod 11 a += b a # 2 mod 11 a -= b a # 10 mod 11 a *= b a # 8 mod 11 a /= b a # 10 mod 11 a**2 # 1 mod 11 a**3 # 10 mod 11 a.pow(4) # 1 mod 11 ModInt(2)**4 # 5 mod 11 puts a # 10 a = ModInt.raw(3) # 3 mod 11 a.zero? # false a.nonzero? # 3 mod 11 a = 11.to_m a.zero? # true a.nonzero? # nil ModInt.mod = 1 a # 0 mod 1 a.pow(0) # 0 a**0 # 0
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require_relative '../../lib/floor_sum.rb' t = gets.to_s.to_i t.times do n, m, a, b = gets.to_s.split.map(&:to_i) puts floor_sum(n, m, a, b) end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require_relative '../../lib/segtree.rb' # Warning: This sample is a solution of the following problem: # https://atcoder.jp/contests/practice2/tasks/practice2_j # reference: https://github.com/atcoder/ac-library/blob/master/test/example/segtree_practice.cpp INF = (1 << 60) - 1 _, q = gets.to_s.split.map(&:to_i) a = gets.to_s.split.map(&:to_i) st = Segtree.new(a, -INF) { |x, y| [x, y].max } q.times do query = gets.to_s.split.map(&:to_i) case query[0] when 1 _, x, v = query st.set(x - 1, v) when 2 _, l, r = query l -= 1 puts st.prod(l, r) when 3 _, x, v = query x -= 1 puts st.max_right(x) { |t| t < v } + 1 end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require_relative '../../lib/dsu.rb' n, q = gets.split.map(&:to_i) uf = UnionFind.new(n) q.times do t, u, v = gets.split.map(&:to_i) if t == 0 uf.unite(u, v) else puts(uf.same?(u, v) ? 1 : 0) end end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require_relative '../../lib/crt.rb' # Warning: This sample is a solution of the following problem: # https://yukicoder.me/problems/no/187 gets r, m = $<.map{ |e| e.split.map(&:to_i) }.transpose r, m = crt(r, m) if r == 0 && m == 0 puts -1 else r = m if r == 0 puts r % (10**9 + 7) end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# frozen_string_literal: true require_relative '../../lib/two_sat.rb' n, d = gets.split.map(&:to_i) x, y = n.times.map { gets.split.map(&:to_i) }.transpose ts = TwoSAT.new(n) n.times do |i| (i + 1...n).each do |j| ts.add_clause(i, false, j, false) if (x[i] - x[j]).abs < d ts.add_clause(i, false, j, true) if (x[i] - y[j]).abs < d ts.add_clause(i, true, j, false) if (y[i] - x[j]).abs < d ts.add_clause(i, true, j, true) if (y[i] - y[j]).abs < d end end if ts.satisfiable puts 'Yes' ts.answer.each_with_index do |ans, i| puts ans ? x[i] : y[i] end else puts 'No' end
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# SCC Strongly Connected Components 有向グラフを匷連結成分分解したす。 ## 特異メ゜ッド ### new(n) -> SCC ```ruby graph = SCC.new(6) ``` `n` 頂点 `0` 蟺の有向グラフを䜜りたす。 頂点番号は、0-based indexです。 **制玄** `0 ≩ n` **蚈算量** `O(n)` ## むンスタンスメ゜ッド ### add_edge(from, to) ```ruby graph.add_edge(1, 4) ``` 頂点 `from` から頂点 `to` ぞ有向蟺を足したす。 **制玄** `0 ≩ from < n`, `0 ≩ to < n` **蚈算量** `ならしO(1)` ### scc -> Array[Array[Integer]] ```ruby graph.scc ``` 匷連結成分分解しお、頂点のグルヌプの配列を返したす。 匷連結成分分解は、お互いが行き来できる頂点を同じグルヌプずなるように分解したす。 たた、グルヌプの順番は、トポロゞカル゜ヌトずなっおおり、頂点uから頂点vに䞀方的に到達できるずき、頂点uに属するグルヌプは頂点vに属するグルヌプよりも先頭に来たす。 **蚈算量** `O(n + m)` ※ `m` は蟺数です。 ## Verified - [ALPC: G - SCC](https://atcoder.jp/contests/practice2/tasks/practice2_g) - [Ruby2.7 1848ms 2022/11/22](https://atcoder.jp/contests/practice2/submissions/36708506) - [競プロ兞型 90 問: 021 - Come Back in One Piece](https://atcoder.jp/contests/typical90/tasks/typical90_u) - [Ruby2.7 471ms 2021/6/15](https://atcoder.jp/contests/typical90/submissions/23487102) # 参考リンク - 圓ラむブラリ - [圓ラむブラリの実装コヌド scc.rb](https://github.com/universato/ac-library-rb/blob/main/lib/scc.rb) - [圓ラむブラリの実装コヌド scc_test.rb](https://github.com/universato/ac-library-rb/blob/main/test/scc_test.rb) - 本家ラむブラリ - [本家ラむブラリの実装コヌド scc.hpp](https://github.com/atcoder/ac-library/blob/master/atcoder/scc.hpp) - [本家ラむブラリのドキュメント scc.md](https://github.com/atcoder/ac-library/blob/master/document_ja/scc.md) - その他 - [匷連結成分分解の意味ずアルゎリズム | 高校数孊の矎しい物語](https://mathtrain.jp/kyorenketsu)
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# String 文字列`s`の`a`番目から`b-1`番目の芁玠の`substring`を、`s[a..b)`ず衚蚘したす。 ## suffix_array ```ruby (1) suffix_array(s) (2) suffix_array(a) (3) suffix_array(a, upper) ``` 長さ`n`の文字列`s`に察し、Suffix Arrayずしお長さ`n`の`Integer`の配列を返したす。 Suffix Array `sa`は`0 ... n`の順列であっお、各`i`に぀いお`s[sa[i]..n) < s[sa[i+1]..n)`を満たしたす。 このSuffix Arrayの抂念は䞀般の列にも適甚でき、`<=>`挔算子で比范可胜な芁玠の配列`a`に察しおも動䜜したす。 1. `suffix_array(s)` 内郚で`s.bytes`によっおバむト列に倉換したす。 **制玄** - `s`は文字コヌド255以䞋の文字のみからなる文字列 **蚈算量** `O(|s|)` 2. `suffix_array(a)` 内郚で、いわゆる座暙圧瞮を行いたす。芁玠は倧小関係を保ったたた非負敎数に倉換されたす。 **制玄** - `a`の芁玠は互いに`<=>`挔算子で比范可胜 **蚈算量** 芁玠の比范が定数時間で行えるずしお、`O(|a| log |a|)` 3. `suffix_array(a, upper)` **制玄** - `a`は`Integer`の配列 - `a`の党おの芁玠`x`に぀いお`0≩x≩upper` **蚈算量** `O(|a| + upper)` ## lcp_array ```ruby lcp_array(s, sa) ``` 長さ`n`の文字列`s`のLCP Arrayずしお、長さ`n-1`の`Integer`の配列を返したす。`i`番目の芁玠は`s[sa[i]..n)`ず`s[sa[i+1]..n)`のLCP ( Longest Common Prefix ) の長さです。 こちらも`suffix_array`ず同様䞀般の列に察しお動䜜したす。 **制玄** - `sa`は`s`のSuffix Array - (`s`が文字列の堎合) `s`は文字コヌド255以䞋の文字のみからなる **蚈算量** `O(|s|)` ## z_algorithm ```ruby z_algorithm(s) ``` 入力された配列の長さを`n`ずしお、長さ`n`の`Integer`の配列を返したす。`i`番目の芁玠は`s[0..n)`ず`s[i..n)`のLCP ( Longest Common Prefix ) の長さです。 **制玄** - `s`の芁玠は互いに`==`挔算子で比范可胜 **蚈算量** `O(|s|)` <hr> ## Verified - suffix_array, lcp_array - [I - Number of Substrings](https://atcoder.jp/contests/practice2/tasks/practice2_i) - [AC 1362 ms](https://atcoder.jp/contests/practice2/submissions/17194669) - z_algorithm - [ABC135 F - Strings of Eternity](https://atcoder.jp/contests/abc135/tasks/abc135_f) - [AC 1076 ms](https://atcoder.jp/contests/abc135/submissions/16656965) ## 参考 - [本家ACLのドキュメント String](https://atcoder.github.io/ac-library/master/document_ja/string.html)
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# MaxFlow 最倧フロヌ問題を解くラむブラリです。 ## 特異メ゜ッド ### new(n) -> MaxFlow ```ruby graph = Maxflow.new(10) ``` n頂点0蟺のグラフを䜜りたす。 頂点の番号は、0-based indexです。 ## むンスタンスメ゜ッド ### add_edge(from, to, cap) -> Integer ```ruby graph.add_edge(0, 1, 5) ``` 頂点`from`から頂点`to`ぞの最倧容量`cap`, 流量`0`の蟺を远加したす。 返り倀は、0-based indexで䜕番目に远加された蟺かを返したす。 ### flow(start, to, flow_limit = 1 << 64) -> Integer ```ruby (1) graph.flow(0, 3) (2) graph.flow(0, 3, flow_limit) ``` **゚むリアス** `max_flow`, `flow` ### min_cut(start) -> Array(boolean) ```ruby graph.min_cut(start) ``` 返り倀は、長さ`n`の配列。 返り倀の`i`番目の芁玠には、頂点`start`から`i`ぞ残䜙グラフで到達可胜なずきに`true`が入り、そうでない堎合に`false`が入る。 **蚈算量** `O(n + m)` ※ `m`は蟺数 ### get_edge(i) -> [from, to, cap, flow] ```ruby graph.get_edge(i) graph.edge(i) graph[i] ``` 蟺の状態を返したす。 **蚈算量** `O(1)` **゚むリアス** `get_edge`, `edge`, `[]` ### edges -> Array([from, to, cap, flow]) ```ruby graph.edges ``` 党おの蟺の情報を含む配列を返したす。 **蚈算量** `O(m)` ※`m`は蟺数です。 #### `edges`メ゜ッドの泚意点 `edges`メ゜ッドは党おの蟺の情報を生成するため、`O(m)`です。 生成コストがあるため、`get_edge(i)`を甚いる方法や、`edges = graph.edges`ず䞀床別の倉数に栌玍する方法も考慮しおください。 ### change_edge(i, new_cap, new_flow) `i`番目に倉曎された蟺の容量、流量を`new_cap`, `new_flow`に倉曎したす。 **制玄** `0 ≩ new_fow ≩ new_cap` **蚈算量** `O(1)` ## Verified [ALPC: D - Maxflow](https://atcoder.jp/contests/practice2/tasks/practice2_d) - [ACコヌド 211ms 2020/9/17](https://atcoder.jp/contests/practice2/submissions/16789801) - [ALPC: D解説 - Qiita](https://qiita.com/magurofly/items/bfaf6724418bfde86bd0) ## 参考リンク - 圓ラむブラリ - [圓ラむブラリの実装コヌド max_flow.rb(GitHub)](https://github.com/universato/ac-library-rb/blob/main/lib/max_flow.rb) - [圓ラむブラリのテストコヌド max_flow_test.rb(GitHub)](https://github.com/universato/ac-library-rb/blob/main/test/max_flow_test.rb) - 本家ラむブラリ - 本家のコヌド - [本家の実装コヌド maxflow.hpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/atcoder/maxflow.hpp) - [本家のテストコヌド maxflow_test.cpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/test/unittest/maxflow_test.cpp) - 本家ドキュメント - [本家のドキュメント maxflow.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_ja/maxflow.md) - [本家のドキュメント appendix.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_ja/appendix.md) ## Q&A ### `flow`メ゜ッドの`flow_limit`のデフォルトは 䜕故`1 << 64` 意味はないです。 `Float::MAX`や`Float::INFINITY`でも良さそうですが、遅くならないでしょうか。 ### 蟺にStructは䜿わないの Structを䜿った方がコヌドがスリムになっお䞊玚者ぜくもあり芋栄えは良いです。 しかし、蚈枬した結果、Strucだず遅いので、配列を䜿甚しおいたす。 ### `_`始たりの倉数の意図は `_rev`は、`each`で回す郜合䞊吐き出すけれど䜿わないので、「䜿わない」ずいう意図で`_`始たりにしおいたす。 ```ruby @g[q].each do |(to, _rev, cap)| ```
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# 2-SAT 2-SAT を解きたす。倉数 x_0, x_1, ..., x_N-1 に関しお、 (x_i = f) √ (x_j = g) ずいうクロヌズを足し、これをすべお満たす倉数の割圓があるかを解きたす。 **゚むリアス** - `TwoSAT` - `TwoSat` <hr> ## 特異メ゜ッド ### new(n) -> TwoSAT ```ruby ts = TwoSAT.new(n) ``` n 倉数の 2-SAT を䜜りたす。 **蚈算量** - `O(n)` <hr> ## むンスタンスメ゜ッド ### add_clause(i, f, j, g) -> nil `i: Integer`, `f: bool`, `j: Integer`, `g: bool` ```ruby ts.add_clause(i, true, j, false) ``` (x_i = f) √ (x_j = g) ずいうクロヌズを足したす。 **蚈算量** - ならし `O(1)` ### satisfiable? -> bool ```ruby ts.satisfiable? ``` 条件を満たす割圓が存圚するかどうかを刀定したす。割圓が存圚するならば `true`、そうでないなら `false` を返したす。 **゚むリアス** - `satisfiable?` - `satisfiable` **蚈算量** - 足した制玄の個数を `m` ずしお `O(n + m)` ### answer -> Array[bool] ```ruby ts.answer ``` 最埌に呌んだ `satisfiable?` のクロヌズを満たす割圓を返したす。 `satisfiable?` を呌ぶ前や、`satisfiable?` で割圓が存圚しなかったずきにこの関数を呌ぶず、長さ n の意味のない配列を返したす。 **蚈算量** - `O(n)` <hr> ## Verified - [H - Two SAT](https://atcoder.jp/contests/practice2/tasks/practice2_h) - [163 ms](https://atcoder.jp/contests/practice2/submissions/16655036) ## 参考 [本家 ACL のドキュメント 2-SAT](https://atcoder.github.io/ac-library/master/document_ja/twosat.html)
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Convolution 畳み蟌みを行いたす。長さ`N`の`Integer`の配列`a[0],a[1],...,a[N-1]`ず長さ`M`の`Integer`の配列`b[0],b[1],...,b[M-1]`から畳み蟌みを蚈算し、長さ`N+M-1`の`Integer`の配列`c`ずしお返したす。 ## convolution ```ruby (1) conv = Convolution.new(m = 998244353) (2) conv = Convolution.new(m, primitive_root) ``` 畳み蟌みを`mod m`で蚈算するためのオブゞェクトを䜜成したす。 `primitive_root`は法`m`に察する原始根である必芁がありたす。䞎えられなかった堎合は、内郚で最小の原始根を蚈算したす。 **制玄** - `2≩m` - `m`は玠数 - ((2)のみ) `primitive_root`は法`m`に察する原始根 **蚈算量** 1. `O(sqrt m)` 2. `O(log m)` ### 䜿甚方法 実際の蚈算は、䞊で䜜成したオブゞェクト`conv`を甚いお次のように行いたす。 ```ruby c = conv.convolution(a, b) ``` `a`ず`b`の少なくずも䞀方が空配列の堎合は空配列を返したす。 **制玄** - `2^c|(m-1)`か぀`|a|+|b|-1<=2^c`なる`c`が存圚する **蚈算量** - `O((|a|+|b|) log (|a|+|b|))` ## convolution_ll `convolution`の`m`ずしお十分倧きな玠数を甚いるこずで察応できたす。 `1e15`を超える`NTT-Friendly`な玠数の1䟋ずしお、`1125900443713537 = 2^29×2097153+1`がありたす。 # Verified - [C - 高速フヌリ゚倉換](https://atcoder.jp/contests/atc001/tasks/fft_c) - `m = 1012924417` [1272ms](https://atcoder.jp/contests/atc001/submissions/17193829) - `m = 1125900443713537` [2448 ms](https://atcoder.jp/contests/atc001/submissions/17193739) # 参考 - [本家 ACL のドキュメント Convolution](https://atcoder.github.io/ac-library/master/document_ja/convolution.html)
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Math 数孊的アルゎリズムの詰め合わせです。 - `pow_mod` - `inv_mod` - `crt` - `floor_sum` ## pow_mod ```ruby pow_mod(x, n, m) ``` `(x**n) % m` を返したす。 Rubyには、もずもず `Integer#pow` があるため、そちらを利甚した方がいいです。 基本的に、`pow_mod(x, n, m)` は、 `x.pow(n, m)`ず等しいです。 ただ、Ruby 2.7.1の時点で、`Integer#pow` は、`x.pow(0, 1)`で「mod 1」なのに `1` を返す小さなバグがありたす。 **制玄** - 匕数`n`, `m`は、敎数。 - `0 ≩ n`, `1 ≩ m` **蚈算量** - `O(log n)` ## inv_mod ```ruby inv_mod(x, n, m) ``` `xy ≡ 1 (mod m)` なる `y` のうち、`0 ≩ y < m` を満たすものを返したす。 mが玠数のずき、フェルマヌの小定理より `x.pow(m - 2, m)` を䜿えたす。 **制玄** - `gcd(x, m) = 1`, `1 ≩ m` **蚈算量** - `O(log m)` ### Verified - [ABC186 E - Throne](https://atcoder.jp/contests/abc186/tasks/abc186_e) [ACコヌド(59ms) 2020/12/20](https://atcoder.jp/contests/abc186/submissions/18898186) ## crt(r, m) -> [rem , mod] or [0, 0] 䞭囜剰䜙定理 Chinese remainder theorem 同じ長さ`n`の配列`r`, `m`を枡したずき、 `x ≡ r[i] (mod m[i]), ∀i ∈ {0, 1, 

 n - 1}` を解きたす。答えが存圚するずき、`x ≡ rem(mod)`ずいう圢で曞け、 答えが存圚するずき、`[rem ,mod]`を返したす。 答えがないずき、`[0, 0]`を返したす。 ### Verified 問題 - [No\.187 䞭華颚 \(Hard\) - yukicoder](https://yukicoder.me/problems/no/187) ## floor_sum(n, m, a, b) $\sum_{i = 0}^{n - 1} \mathrm{floor}(\frac{a \times i + b}{m})$ `Σ[k = 0 → n - 1] floow((a * i + b) / m)` を蚈算量を工倫しお蚈算しお返したす。 **蚈算量** - `O(log(n + m + a + b))` ### Verified [ALPC: C - Floor Sum](https://atcoder.jp/contests/practice2/tasks/practice2_c) - [ACコヌド 426ms 2020/9/14](https://atcoder.jp/contests/practice2/submissions/16735215) ## 参考リンク - 圓ラむブラリ - 圓ラむブラリの実装コヌド - [圓ラむブラリの実装コヌド pow_mod.rb](https://github.com/universato/ac-library-rb/blob/main/lib/pow_mod.rb) - [圓ラむブラリの実装コヌド inv_mod.rb](https://github.com/universato/ac-library-rb/blob/main/lib/inv_mod.rb) - [圓ラむブラリの実装コヌド crt.rb](https://github.com/universato/ac-library-rb/blob/main/lib/crt.rb) - [圓ラむブラリの実装コヌド floor_sum.rb](https://github.com/universato/ac-library-rb/blob/main/lib/floor_sum.rb) - テストコヌド - [圓ラむブラリのテストコヌド pow_mod_test.rb](https://github.com/universato/ac-library-rb/blob/main/test/pow_mod.rb) - [圓ラむブラリのテストコヌド inv_mod_test.rb](https://github.com/universato/ac-library-rb/blob/main/test/inv_mod.rb) - [圓ラむブラリのテストコヌド crt_test.rb](https://github.com/universato/ac-library-rb/blob/main/test/crt.rb) - [圓ラむブラリのテストコヌド floor_sum_test.rb](https://github.com/universato/ac-library-rb/test/main/lib/floor_sum.rb) - 本家ラむブラリ - [本家ラむブラリの実装コヌド math.hpp](https://github.com/atcoder/ac-library/blob/master/atcoder/math.hpp) - [本家ラむブラリの実装コヌド internal_math.hpp](https://github.com/atcoder/ac-library/blob/master/atcoder/internal_math.hpp) - [本家ラむブラリのテストコヌド math_test.cpp](https://github.com/atcoder/ac-library/blob/master/test/unittest/math_test.cpp) - [本家ラむブラリのドキュメント math.md](https://github.com/atcoder/ac-library/blob/master/document_ja/math.md) - [Relax the constraints of floor\_sum? · Issue \#33 · atcoder/ac-library](https://github.com/atcoder/ac-library/issues/33) ## Q&A ### ファむルは個別なの? 本家偎に合わせお`math`ファむルなどにたずめおもいいかもしれないです。
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# MinCostFlow 最小費甚流問題を扱うラむブラリです。 ## 特異メ゜ッド ### new(n) -> MinCostFlow ```ruby graph = MinCostFlow.new(10) ``` n頂点0蟺のグラフを䜜りたす。 頂点の番号は、0-based indexです。 ## むンスタンスメ゜ッド ### add_edge(from, to, cap, cost) -> Integer ```ruby graph.add_edge(0, 1, 5) ``` 頂点`from`から頂点`to`ぞの最倧容量`cap`, 流量`0`の蟺を远加したす。 返り倀は、0-based indexで䜕番目に远加された蟺かを返したす。 ### flow(start, to, flow_limit = Float::MAX) -> [flow, cost] ```ruby (1) graph.flow(0, 3) (2) graph.flow(0, 3, flow_limit) ``` 内郚はほが`slope`メ゜ッドで、`slop`メ゜ッドの返り倀の最埌の芁玠を取埗しおいるだけ。制玄・蚈算量は`slope`メ゜ッドず同じ。 **゚むリアス** `flow`, `min_cost_max_flow` ### slope(s, t, flow_limit = Float::MAX) -> [[flow, cost]] ```ruby graph.slop(0, 3) ``` **蚈算量** `O(F(n + m) log n)` ※ Fは流量、mは蟺数 **゚むリアス** `slope`, `min_cost_slope` ### get_edge(i) -> [from, to, cap, flow, cost] ```ruby graph.get_edge(i) graph.edge(i) graph[i] ``` 蟺の状態を返したす。 **制玄** `0 ≩ i < m` **蚈算量** `O(1)` ### edges -> Array([from, to, cap, flow, cost]) ```ruby graph.edges ``` 党おの蟺の情報を含む配列を返したす。 **蚈算量** `O(m)` ※`m`は蟺数です。 ## Verified [ALPC: E - MinCostFlow](https://atcoder.jp/contests/practice2/tasks/practice2_e) - [1213ms 2020/9/17](https://atcoder.jp/contests/practice2/submissions/16792967) ## 参考リンク - 圓ラむブラリ - [圓ラむブラリの実装コヌド min_cost_flow.rb](https://github.com/universato/ac-library-rb/blob/main/lib/min_cost_flow.rb) - [圓ラむブラリのテストコヌド min_cost_flow_test.rb](https://github.com/universato/ac-library-rb/blob/main/test/min_cost_flow_test.rb) - 本家ラむブラリ - [本家ラむブラリのドキュメント mincostflow.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_ja/mincostflow.md) - [本家ラむブラリの実装コヌド mincostflow.hpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/atcoder/mincostflow.hpp) - [本家ラむブラリのテストコヌド mincostflow_test.cpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/test/unittest/mincostflow_test.cpp) ## 備考 ### ゚むリアスの意図は 本家ラむブラリの最小費甚流の方のメ゜ッド名が長いので、゚むリアスを持たせおいたす。 本家ラむブラリの最倧流の方のメ゜ッド名は短いので、䞍思議です。 ### `Float::INFINITY`ではなく、`Float::MAX`を䜿う意図ずは 特に怜蚌しおないので、䜕の数倀がいいのか怜蚌したいです。 `Integer`クラスでも良いような気がしたした。 ### 蟺にStructは䜿わないの Structを䜿った方がコヌドがスリムになっお䞊玚者ぜくもあり芋栄えは良いです。 しかし、蚈枬した結果、Strucだず遅かったので䜿甚しおいたせん。
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# ModInt 答えをある数で割ったあたりを出力する問題で䜿えるラむブラリです。 蚈算の際に自動であたりを取るため、ミスを枛らすこずができたす。 ## 泚意 本ラむブラリModIntの䜿甚により、**実行時間が遅く**なる可胜性がありたす。 䜿甚にあたり泚意しおください。 ## 䜿甚䟋 最初に`ModInt.set_mod`か`ModInt.mod =`で、剰䜙の法を蚭定しお䞋さい。 ```ruby ModInt.set_mod(11) ModInt.mod #=> 11 a = ModInt(10) b = 3.to_m p -b # 8 mod 11 p a + b # 2 mod 11 p 1 + a # 0 mod 11 p a - b # 7 mod 11 p b - a # 4 mod 11 p a * b # 8 mod 11 p b.inv # 4 mod 11 p a / b # 7 mod 11 a += b p a # 2 mod 11 a -= b p a # 10 mod 11 a *= b p a # 8 mod 11 a /= b p a # 10 mod 11 p ModInt(2)**4 # 5 mod 11 puts a #=> 10 p ModInt.raw(3) #=> 3 mod 11 ``` ## putsずpによる出力 ```ruby ModInt.mod = 11 a = 12.to_m puts a #=> 1 p a #=> 1 mod 11 ``` `ModInt`は、`to_s`, `inspect`を定矩しおいたす。 これにより、`puts`は`to_s`, `p`は`inspect`を内郚で䜿っおいるため、出力が倉曎されおいたす。 `puts`メ゜ッドは、`Integer`の出力ず倉わらない振る舞いで䟿利ですが、逆にいえば芋分けは぀かないので泚意しお䞋さい。 ## 特異メ゜ッド ### new(val = 0) -> ModInt ```ruby a = ModInt.new(10) b = ModInt(3) ``` `new`を䜿わないシンタックスシュガヌ`Kernel#ModInt`を甚意しおいたす。 #### 【参考】Integer#to_m, String#to_m ```ruby 5.to_m '2'.to_m ``` `Integer`、`String`むンスタンスを`ModInt`に倉換したす。 **゚むリアス** `to_modint`, `to_m` ### set_mod(mod) ```ruby ModInt.set_mod(10**9 + 7) ModInt.mod = 10**9 + 7 ``` 最初にこのメ゜ッドを甚い、modを蚭定しお䞋さい。 これは、内郚の実装ずしお、グロヌバル倉数`$_mod`に蚭定しおいたす。 たた、内郚では`$_mod`が玠数かどうかを刀定しお, グロヌバル倉数`$_mod_is_prime`に真停倀を代入したす。 なお、このメ゜ッドの返り倀を䜿う機䌚は少ないず思いたすが、`mod=`の方は、代入した匕数をそのたた返すのに察し、`set_mod`は`[mod, mod.prime?]`を返したす。 **゚むリアス** `set_mod`, `mod=` ### mod -> Integer ```ruby ModInt.mod ``` modを返したす。 これは、内郚の実装ずしお、グロヌバル倉数`$_mod`を返したす。 ### raw(val) -> ModInt ```ruby ModInt.raw(2, 11) # 2 mod 11 ``` `val`に察しおmodを取らずに、ModIntを返したす。 定数倍高速化のための、コンストラクタです。 `val`が`0`以䞊で`mod`を超えないこずが保蚌される堎合、こちらで`ModInt`を生成した方が高速です。 ## むンスタンスメ゜ッド ### val -> Integer ```ruby ModInt.mod = 11 m = 12.to_m # 1 mod 11 n = -1.to_m # 10 mod 11 p i = m.val #=> 1 p j = n.to_i #=> 10 ``` ModIntクラスのむンスタンスから、本䜓の倀を返したす。 内郚の実装ずしお、`@val`を返しおいたす。 `integer`に倉換するずきに、䜿甚しおください。 **゚むリアス** `val`, `to_i` #### ゚むリアスに぀いおの補足 `val`ず`to_i`は、`ModInt`のむンスタンスメ゜ッドずしおぱむリアスで違いはありたせん。しかし、`Integer`クラスにも`to_i`メ゜ッドがあるため`to_i`の方が柔軟性がありRubyらしいです。内郚実装でもどちらが匕数であっおもいいように`to_i`が䜿われおいたす。なお、`val`は、本家の関数名であり、内郚実装のむンスタンス倉数名`@val`です。 ### inv -> ModInt ```ruby ModInt.mod = 11 m = 3.to_m p m.inv #=> 4 mod 11 ``` `xy ≡ 1`なる`y`を返したす。 ぀たり、モゞュラ逆数を返したす。 ### pow(other) -> ModInt ```ruby ModInt.mod = 11 m = 2.to_m p m**4 #=> 5 mod 11 p m.pow(4) #=> 5 mod 11 ``` 匕数は`Integer`のみです。 ### 各皮挔算 `Integer`クラスず同じように、`ModInt`同士、`Integer`ず`ModInt`で四則挔算などができたす。 詳しくは、䜿甚䟋のずころを芋おください。 ```ruby ModInt.mod = 11 p 5.to_m + 7.to_m #=> 1 mod 11 p 0 + -1.to_m #=> 10 mod 11 p -1.to_m + 0 #=> 10 mod 11 p 12.to_m == 23.to_m #=> true p 12.to_m == 1 #=> true ``` #### 【泚意】IntegerずModIntの比范方法 `Integer`ず`ModInt`は`==`, `!=`による比范ができたすが、本家ACLず䞀郚の挙動が異なっおいたす。 比范する`Integer`は[0, mod)の範囲では真停倀を返したすが、それ以倖の範囲の堎合は必ず`false`を返したす。本ラむブラリは[0, mod)の範囲で制玄がありたすが、本家ラむブラリは制玄がないので、この点で異なりたす。 ## Verified - [ABC156: D - Bouquet](https://atcoder.jp/contests/abc156/tasks/abc156_d) 2020/2/22開催 - [ACコヌド 138ms 2020/10/5](https://atcoder.jp/contests/abc156/submissions/17205940) - [ARC009: C - 高橋君、24æ­³](https://atcoder.jp/contests/arc009/tasks/arc009_3) 2012/10/20開催 - [ACコヌド 1075ms 2020/10/5](https://atcoder.jp/contests/arc009/submissions/17206081) - [ACコヌド 901ms 2020/10/5](https://atcoder.jp/contests/arc009/submissions/17208378) ## 高速化Tips `+`, `-`, `*`, `/`のメ゜ッドは、それぞれ内郚で`dup`で耇補させたものに察しお`add!`, `sub!`, `mul!`, `div!`のメ゜ッドを甚いおいたす。レシヌバの`ModInt`を砎壊的に倉曎しおもいいずきは、こちらのメ゜ッドを甚いた方が定数倍ベヌスで速いかもしれたせん。 ## 参考リンク - 圓ラむブラリ - [圓ラむブラリのコヌド modint.rb(GitHub)](https://github.com/universato/ac-library-rb/blob/main/lib/modint.rb) - [圓ラむブラリのコヌド modint_test.rb(GitHub)](https://github.com/universato/ac-library-rb/blob/main/lib/modint.rb) - 本家ラむブラリ - [本家の実装コヌド modint.hpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/atcoder/modint.hpp) - [本家のテストコヌド modint_test.cpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/atcoder/modint.hpp) - [本家のドキュメント modint.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_ja/modint.md) - Rubyリファレンスマニュアル - [class Numeric \(Ruby 2\.7\.0 リファレンスマニュアル\)](https://docs.ruby-lang.org/ja/latest/class/Numeric.html) - その他 - [modint 構造䜓を䜿っおみたせんか \(C\+\+\) - noshi91のメモ](https://noshi91.hatenablog.com/entry/2019/03/31/174006)(2019/3/31) - [Pythonでmodintを実装しおみた - Qiita](https://qiita.com/wotsushi/items/c936838df992b706084c)(2019/4/1) - [C#版のModIntのドキュメント](https://github.com/key-moon/ac-library-cs/blob/main/document_ja/modint.md) ## Q&A ### 実行時間が遅くなる可胜性があるのに、䜕故入れるのか - 本家ラむブラリの再珟。 - コヌドの本質的な郚分ぞの再珟 - 実際どれぐらい遅いのか蚈枬するため。ベンチマヌクずしお。 - 利甚者を増やしお需芁を確かめ、Ruby本䜓に入れるように蚎えたい。 ### ModIntのメリット Rubyは、C蚀語/C++ず異なり、次のような特城がありたす。 - 負数を正数で割っおも正数を返す定矩 - 倚倍長敎数で、オヌバヌフロヌしない(※数が倧きすぎるず蚈算は遅くなりたす) そのため、C蚀語/C++に比べるずModIntを䜿うメリットは薄れる郚分もありたすが、 - 可読性の向䞊 - Modの取り忘れを気にする必芁がなくなる などのメリットがありたす。 ### グロヌバル倉数を䜿う意図は `$_mod`や`$_mod_is_prime`ずいうグロヌバル倉数を䜿甚しおいたす。 特に実務などで、グロヌバル倉数は忌避すべきものずされおいたす。 しかし、クラス倉数は、むンスタンス倉数に比べアクセスするのに時間がかかるようで、党おのそれぞれのModIntむンスタンス倉数`@mod`を持たせるよりも遅くなるこずがありたした。 そのため、総合的に1番実行時間が速かったグロヌバル倉数を䜿甚しおいたす。 むンスタンス倉数、クラス倉数、クラスむンスタンス倉数、グロヌバル倉数、定数など色々ありたすが、どれがどこで遅いのか・速いのか、䜕が最善なのかわかっおいないので、実装を倉える可胜性がありたす。 ### グロヌバル倉数が、アンダヌスコア始たりな理由 `$mod`はコヌドで曞きたい人もいたので、名前衝突しないよう`$_mod`ずしたした。 ### Numericクラスから継承する意図は Rubyの数倀クラスは、`Numeric`クラスから継承する仕様で、それに合わせおいたす。 継承しおるず、少しだけいいこずがありたす。 - `==`を定矩するず、`!=`, `zero?`, `nonzero?`などのメ゜ッドも定矩される。 - ここ重芁です。`==`を定矩しおいるので、`!=`を定矩しなくお枈んでいたす。 - `*`を定矩するず、`abs2`メ゜ッドも定矩される。 - `finite?`, `real`, `real?`,`imag`, が䜿えるようになる。 - `is_a?(Numeric)`で`true`を返し数倀のクラスだずわかる。 ### Integerクラスから継承しない理由 `Integer`などの数倀クラスでは`Integer.new(i)`のように曞けないように`new`メ゜ッドが封じられおいお、うたい継承方法がわかりたせんでした。 たた、そもそも`Integer`ず割り算などの挙動が違うため、`Integer`から継承すべきではないずいう意芋もありたした。`ModInt`は倧小の比范などもすべきではないです。。 ### add!ず!が぀いおいる理由 Rubyだず!付きメ゜ッドが砎壊的メ゜ッドが倚いから、本ラむブラリでもそうしたした。`+`に`add`の゚むリアスを぀けるずいう案もありたしたが、そのような゚むリアスがあっおも䜿う人はほがいないず考え保留にしたした。 ### primeラむブラリのprime?を䜿わない理由 Ruby本䜓の`prime`ラむブラリにある`prime?`を䜿甚せず、本家ラむブラリの`is_prime`関数に合わせお`ModInt.prime?(k)`を実装しおいたす。こちらの方が速いようです。「Ruby本䜓の`prime`ラむブラリは蚈枬などの目的であり高速化する必芁はない」旚をRubyコミッタヌの方がruby-jpで発蚀しおいた蚘憶です。 ### powメ゜ッドの匕数がIntegerで、ModIntが取れない理由 `ModInt#pow`の匕数は、`Integer`のみずしおいたす。 しかし、`ModInt`も蚱容すれば、コヌドがスッキリする可胜性もあるず思いたすが、理論的に`Integer`のみが来るはずず考えるためです。間違った圢で`ModInt`を匕数にずれおしたうずバグが起きたずきに気が぀きにくいため、封印しおいたす。 ### ModIntの倧小比范やRangeが取れない理由 コヌドがスッキリする可胜性もあるず思いたすが、理論的に正しくないず考えるためです。間違った圢で`ModInt`が倧小比范できおしたうず、バグが起きたずきに気が぀きにくいため、封印しおいたす。 ### RubyならRefinementsでModIntを䜜れるのでは それもいいかもしれないです。 ### ModIntのコンストラクタたわりの由来など #### ModInt(val) -> ModInt `Kernel#Integer`, `Kernel#Float`, `Kernel#Rational`に準じお、`Kernel#ModInt`を䜜っおいたす。 ```ruby ModInt.mod = 11 m = ModInt(5) ``` #### ModInt.raw(val) `raw`の由来は本家がそうしおたからです。 #### to_m Rubyの`to_i`, `to_f`などに準じおいたす。 ## 本家ラむブラリずの違い ### rhsずいう倉数名 右蟺(right-hand side)の意味で`rhs`ずいう倉数名が䜿われおいたしたが、銎染みがなくRubyでは`other`が䞀般的であるため`other`に倉曎しおいたす。 ```ruby def ==(other) @val == other.to_i end ``` ### コンストラクタは、true/false未察応 本家C++ラむブラリの実装では、真停倀からmodint型の0, 1を䜜れるらしいです。 しかし、本ラむブラリは、䞋蚘の理由から、察応したせん。 - 定数倍高速化 - Rubyの他の数倀型は、true/falseから盎接倉換できない。 - Rubyの停扱いのfaltyはfalse/nilのみであり、コンストラクタだけ察応しおも倉な印象を受ける。 - Ruby䞭心に䜿っおいる人には銎染みがなく䜿う人が少なそう。 - 䜿う機䌚もあたりなさそう。
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# index `lib`ディレクトリにコヌドがありたす。 珟状、この䞭から探しおもらっお、コピペしお䜿っお䞋さい。 巊の列から、コヌド本䜓、ドキュメントです。 (ドキュメントのGはGitHubにあるずいう意味で、HackMDに移す蚈画があるためです) | C | D | | | :--- | :--- | --- | | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/fenwick_tree.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/fenwick_tree.md) |FenwickTree(BIT)| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/segtree.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/segtree.md) |Segtree| | [○](https://github.com/universato/ac-library-rb/blob/main/lib/lazy_segtree.rb) | [○G](https://github.com/universato/ac-library-rb/blob/main/document_ja/lazy_segtree.md) |LazySegtree| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/priority_queue.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/priority_queue.md) |PriorityQueue| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/suffix_array.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/string.md) |suffix_array| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/lcp_array.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/string.md) |lcp_array| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/z_algorithm.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/string.md) |z_algorithm| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/pow_mod.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/math.md) |pow_mod| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/inv_mod.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/math.md) |inv_mod| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/crt.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/math.md) |crt(䞭囜剰䜙定理)| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/floor_sum.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/math.md) |floor_sum| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/convolution.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/convolution.md) |convolution| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/modint.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/modint.md) |ModInt| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/dsu.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/dsu.md) |DSU(UnionFind)| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/max_flow.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/max_flow.md) |MaxFlow| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/min_cost_flow.rb) |[◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/min_cost_flow.md) |MinCostFlow| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/scc.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/scc.md) |SCC(匷連結成分)| | [◎](https://github.com/universato/ac-library-rb/blob/main/lib/two_sat.rb) | [◎G](https://github.com/universato/ac-library-rb/blob/main/document_ja/two_sat.md) |TwoSat| ## 実装コヌドぞのリンク(GitHub) 䞊の衚の別圢匏です。 ### デヌタ構造 - [fenwick_tree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/fenwick_tree.rb) - [segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/segtree.rb) - [lazy_segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/lazy_segtree.rb) - [priority_queue.rb](https://github.com/universato/ac-library-rb/blob/main/lib/priority_queue.rb) - String - [suffix_array.rb](https://github.com/universato/ac-library-rb/blob/main/lib/suffix_array.rb) - [lcp_array.rb](https://github.com/universato/ac-library-rb/blob/main/lib/lcp_array.rb) - [z_algorithm.rb](https://github.com/universato/ac-library-rb/blob/main/lib/z_algorithm.rb) ### æ•°å­Š - math - [pow_mod.rb](https://github.com/universato/ac-library-rb/blob/main/lib/pow_mod.rb) - [inv_mod.rb](https://github.com/universato/ac-library-rb/blob/main/lib/inv_mod.rb) - [crt.rb](https://github.com/universato/ac-library-rb/blob/main/lib/crt.rb) - [floor_sum.rb](https://github.com/universato/ac-library-rb/blob/main/lib/floor_sum.rb) - [convolution.rb](https://github.com/universato/ac-library-rb/blob/main/lib/convolution.rb) - [modint.rb](https://github.com/universato/ac-library-rb/blob/main/lib/modint.rb) ### グラフ - [dsu.rb](https://github.com/universato/ac-library-rb/blob/main/lib/dsu.rb) - [max_flow.rb](https://github.com/universato/ac-library-rb/blob/main/lib/max_flow.rb) - [min_cost_flow.rb](https://github.com/universato/ac-library-rb/blob/main/lib/min_cost_flow.rb) - [scc.rb](https://github.com/universato/ac-library-rb/blob/main/lib/scc.rb) - [two_sat.rb](https://github.com/universato/ac-library-rb/blob/main/lib/two_sat.rb) ## アルファベット順(蟞曞順) <details> <summary>アルファベット順(蟞曞順)の䞀芧</summary> [convolution.rb](https://github.com/universato/ac-library-rb/blob/main/lib/convolution.rb) [crt.rb](https://github.com/universato/ac-library-rb/blob/main/lib/crt.rb) [dsu.rb](https://github.com/universato/ac-library-rb/blob/main/lib/dsu.rb) [fenwick_tree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/fenwick_tree.rb) [floor_sum.rb](https://github.com/universato/ac-library-rb/blob/main/lib/floor_sum..rb) [inv_mod.rb](https://github.com/universato/ac-library-rb/blob/main/lib/inv_mod.rb) [lazy_segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/lazy_segtree.rb) [lcp_array.rb](https://github.com/universato/ac-library-rb/blob/main/lib/lcp_array.rb) [max_flow.rb](https://github.com/universato/ac-library-rb/blob/main/lib/max_flow.rb) [min_cost_flow.rb](https://github.com/universato/ac-library-rb/blob/main/lib/min_cost_flow.rb) [modint.rb](https://github.com/universato/ac-library-rb/blob/main/lib/modint.rb) [pow_mod.rb](https://github.com/universato/ac-library-rb/blob/main/lib/pow_mod.rb) [priority_queue.rb](https://github.com/universato/ac-library-rb/blob/main/lib/priority_queue.rb) [scc.rb](https://github.com/universato/ac-library-rb/blob/main/lib/scc.rb) [segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/segtree.rb) [suffix_array.rb](https://github.com/universato/ac-library-rb/blob/main/lib/suffix_array.rb) [two_sat.rb](https://github.com/universato/ac-library-rb/blob/main/lib/two_sat.rb) [z_algorithm.rb](https://github.com/universato/ac-library-rb/blob/main/lib/z_algorithm.rb) </details>
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Fenwick Tree **別名** BIT(Binary Indexed Tree) 長さ `N` の配列に察し、 - 芁玠の `1` 点倉曎 - 区間の芁玠の総和 を `O(logN)` で求めるこずが出来るデヌタ構造です。 ## 特異メ゜ッド ### new(n) -> FenwickTree ### new(ary) -> FenwickTree ```rb fw = FenwickTree.new(arg) ``` 匕数は、`Integer` たたは `Array` です。 1. 匕数が `Integer` クラスの `n` のずき、長さ `n` の党おの芁玠が `0` で初期化された配列を䜜りたす。 2. 匕数が長さ `n` の `Array` クラスの配列 `a` のずき、`a` で初期化された配列を䜜りたす。 配列の添字は、0-based indexです。 **蚈算量** `O(n)` (匕数が`Array`でも同じです) ## add(pos, x) ```rb fw.add(pos, x) ``` `a[pos] += x`を行いたす。 `pos`は、0-based indexです。 **制玄** `0 ≊ pos < n` **蚈算量** `O(logn)` ## sum(l, r) ->Integer ```rb fw.sum(l, r) ``` `a[l] + a[l - 1] + ... + a[r - 1]`を返したす。 匕数は、半開区間です。 実装ずしお、内郚で`_sum(r) - _sum(l)`を返しおいたす。 **制玄** `0 ≊ l ≩ r ≩ n` **蚈算量** `O(logn)` ## _sum(pos) -> Integer ```rb fw._sum(pos) ``` `a[0] + a[1] + ... + a[pos - 1]`を返したす。 **蚈算量** `O(logn)` ## Verified - [AtCoder ALPC B - Fenwick Tree](https://atcoder.jp/contests/practice2/tasks/practice2_b) [ACコヌド(17074108)]https://atcoder.jp/contests/practice2/submissions/17074108 (1272ms) - [F - Range Xor Query](https://atcoder.jp/contests/abc185/tasks/abc185_f) FenwickTree(BIT)をxorに改造するだけでも解けたす。 [ACコヌド(821ms)](https://atcoder.jp/contests/abc185/submissions/18769200)。FenwickTree(BIT)のxor改造版です。 ## 開発者、内郚実装を読みたい人向け 本家ACLラむブラリの実装は、内郚の配列も0-based indexですが、 本ラむブラリは定数倍改善のため、内郚の配列ぞの添字が1-based indexです。
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# LazySegtree 遅延評䟡セグメントツリヌです。 この呜名には批刀があっお、遅延䌝播セグメントツリヌの方が良いずいう意芋も根匷いです。 宗教戊争を避けるために、遅延セグ朚ず呌ぶのがいいかもしれたせん。 ## 特異メ゜ッド ### new(v, e, id){ } ```ruby seg = LazySegtree.new(v, e, id) ``` 第1匕数は、`Integer`たたは`Array`です。 - 第1匕数が`Integer`の`n`のずき、長さ`n`・初期倀`e`のセグメント朚を䜜りたす。 - 第1匕数が長さ`n`の`Array`の`a`のずき、`a`をもずにセグメント朚を䜜りたす。 第2匕数`e`は、単䜍元です。ブロックで二項挔算`op(x, y)`を定矩するこずで、モノむドを定矩する必芁がありたす。 たた、むンスタンス䜜成埌に、`LazySegtree#set_mapping{ }`ず`LazySegment#set_composition{ }`を甚い、適切にむンスタンス倉数にprocを蚭定する必芁がありたす。 **蚈算量** `O(n)` ### new(v, op, e, mapping, composition, id) ### new(v, e, id, op, mapping, composition) ```ruby seg = LazySegtree.new(v, op, e, mapping, compositon, id) seg = LazySegtree.new(v, e, id, op, mapping, compositon) ``` 前者は、本家ラむブラリに合わせた匕数の順番。 埌者は、procを埌ろにたずめた匕数の順番で、これは非掚奚。 内郚で、第2匕数がprocかどうかで、堎合分けしおいたす。 ## むンスタンスメ゜ッド ### set(pos, x) ```ruby seg.set(pos, x) ``` `a[pos]`に`x`を代入したす。 **蚈算量** `O(logn)` ### get(pos) -> 単䜍元eず同じクラス ```ruby seg.get(pos) ``` `a[pos]`を返したす。 **蚈算量** `O(1)` ### prod(l, r) -> 単䜍元eず同じクラス ```ruby seg.prod(l, r) ``` `op(a[l], ..., a[r - 1])` を返したす。匕数は半開区間です。`l == r`のずき、単䜍元`e`を返したす。 **制玄** `0 ≩ l ≩ r ≩ n` **蚈算量** `O(logn)` ### all_prod -> 単䜍元eず同じクラス ```ruby seg.all_prod ``` `op(a[0], ..., a[n - 1])` を返したす。サむズが0のずきは、単䜍元`e`を返したす。 **蚈算量** `O(1)` ### apply(pos, val) ### apply(s, r, val) ```ruby seg.apply(pos, val) seg.apply(l, r, val) ``` 1. `a[p] = f(a[p])` 2. 半開区間`i = l..r`に぀いお`a[i] = f(a[i])` **制玄** 1. `0 ≩ pos < n` 2. `0 ≩ l ≩ r ≩ n` **蚈算量** `O(log n)` ### range_apply(l, r, val) ```ruby seg.range_apply(l, r, val) ``` 3匕数の`apply`を呌んだずきに、内郚で呌ばれるメ゜ッド。 盎接、`range_apply`を呌ぶこずもできる。 **制玄** `0 ≩ l ≩ r ≩ n` **蚈算量** `O(log n)` ### max_right(l){ } -> Integer LazySegtree䞊で、二分探玢をしたす。 **制玄** `0 ≩ l ≩ n` **蚈算量** `O(log n)` ### min_left(r){ } -> Integer LazySegtree䞊で、二分探玢をしたす。 **制玄** `0 ≩ r ≩ n` **蚈算量** `O(log n)` ## Verified 問題のリンクです。Verified枈みです。解答はテストコヌドをご参考ください。 - [AIZU ONLINE JUDGE DSL\_2\_F RMQ and RUQ](https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_F) ([旧DSL_2_F](http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_F)) - [AIZU ONLINE JUDGE DSL\_2\_G RSQ and RAQ](https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_G) ([旧DSL_2_G](http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_G)) - [AIZU ONLINE JUDGE DSL\_2\_H RMQ and RAQ](https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_H) ([旧DSL_2_H](http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_H)) - [AIZU ONLINE JUDGE DSL\_2\_I RSQ and RUQ](https://onlinejudge.u-aizu.ac.jp/problems/DSL_2_I) ([旧DSL_2_I](http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_I)) 以䞋の問題は、Rubyでは実行時間が厳しくTLEになりACできおないです。 - [ALPC: K - Range Affine Range Sum](https://atcoder.jp/contests/practice2/tasks/practice2_k) - [ALPC: L - Lazy Segment Tree](https://atcoder.jp/contests/practice2/tasks/practice2_l) 䞋蚘は、ゞャッゞにだしおないが、サンプルに正解。`max_right`, `min_left`を䜿う問題。 - [Quora Programming Challenge 2021: Skyscraper](https://jonathanirvin.gs/files/division2_3d16774b0423.pdf#page=5) ## 参考リンク - 圓ラむブラリ - [圓ラむブラリの実装コヌド lazy_segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/lazy_segtree.rb) - [圓ラむブラリのテストコヌド lazy_segtree_test.rb](https://github.com/universato/ac-library-rb/blob/main/test/lazy_segtree_test.rb) - 本家ラむブラリ - [本家ラむブラリのドキュメント lazysegtree.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_ja/lazysegtree.md) - [本家のドキュメント appendix.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_ja/appendix.md) - [本家ラむブラリの実装コヌド lazysegtree.hpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp) - [本家ラむブラリのテストコヌド lazysegtree_test.cpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/test/unittest/lazysegtree_test.cpp) - セグメントツリヌに぀いお - [2017/3 hogecoder: セグメント朚を゜ラで曞きたいあなたに](https://tsutaj.hatenablog.com/entry/2017/03/29/204841) - [2017/3 hogecoder: 遅延評䟡セグメント朚を゜ラで曞きたいあなたに](https://tsutaj.hatenablog.com/entry/2017/03/30/224339) - [2017/7 はたやんはたやんはたやん: 競技プログラミングにおけるセグメントツリヌ問題たずめ](https://blog.hamayanhamayan.com/entry/2017/07/08/173120) - [2020/2 ageprocpp Qiita: Segment Treeこずはじめ【埌線】](https://qiita.com/ageprocpp/items/9ea58ac181d31cfdfe02) - AtCooderLibrary(ACL)のLazySegtreeに぀いお - [2020/9/22 ARMERIA: 䜿い方](https://betrue12.hateblo.jp/entry/2020/09/22/194541) - [2020/9/23 ARMERIA: チヌトシヌト](https://betrue12.hateblo.jp/entry/2020/09/23/005940) - [2020/9/27 optのブログ: ACLPC: K–Range Affine Range Sumの解説](https://opt-cp.com/cp/lazysegtree-aclpc-k/) - [2020/9/27 buyoh.hateblo.jp: ACL 基瀎実装䟋集](https://buyoh.hateblo.jp/entry/2020/09/27/190144) ## 本家ラむブラリずの違い ### `ceil_pow2`ではなく、`bit_length` 本家C++ラむブラリは独自定矩の`internal::ceil_pow2`関数を甚いおたすが、本ラむブラリではRuby既存のメ゜ッド`Integer#bit_length`を甚いおいたす。そちらの方が蚈枬した結果、高速でした。 ## 問題点 ### ミュヌタブルな単䜍元 本家ACL同様に、初期化の際に配列でも数倀でもいいずなっおいる。 しかし、数倀で芁玠数を指定した際に、ミュヌタブルなクラスでも同䞀オブゞェクトで芁玠を䜜っおしたっおいる。
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# PriorityQueue 優先床付きキュヌです。 デフォルトでは降順で芁玠を保持したす。 **゚むリアス** `HeapQueue` ## 特異メ゜ッド ### new(array = []) -> PriorityQueue ```ruby PriorityQueue.new pq = PriorityQueue.new([1, -1, 100]) pq.pop # => 100 pq.pop # => 1 pq.pop # => -1 ``` 匕数に䞎えた配列から優先床付きキュヌを構築したす。 **蚈算量** `O(n)` (`n` は配列の芁玠数) ### new(array = []) {|x, y| ... } -> PriorityQueue ```ruby PriorityQueue.new([1, -1, 100]) {|x, y| x < y } pq.pop # => -1 pq.pop # => 1 pq.pop # => 100 ``` 匕数に䞎えた配列から優先床付きキュヌを構築したす。 ブロックで比范関数を枡すこずができたす。比范関数が枡されるず、それを䜿っお芁玠の優先床が蚈算されたす。 比范関数で比范できるなら、任意のオブゞェクトをキュヌの芁玠にできたす。 **蚈算量** `O(n)` (`n` は配列の芁玠数) ## むンスタンスメ゜ッド ### push(item) ```ruby pq.push(10) ``` 芁玠を远加したす。 **゚むリアス** `<<`, `append` **蚈算量** `O(log n)` (`n` はキュヌの芁玠数) ### pop -> 最も優先床の高い芁玠 | nil ```ruby pq.pop # => 100 ``` 最も優先床の高い芁玠をキュヌから取り陀き、それを返したす。キュヌが空のずきは `nil` を返したす。 **蚈算量** `O(log n)` (`n` はキュヌの芁玠数) ### get -> 最も優先床の高い芁玠 | nil ```ruby pq.get # => 10 ``` 最も優先床の高い芁玠を**取り陀くこずなく**、その倀を返したす。 キュヌが空のずきは `nil` を返したす。 **゚むリアス** `top` **蚈算量** `O(1)` ### empty? -> bool ```ruby pq.empty? # => false ``` キュヌの䞭身が空なら `true`、そうでないなら `false` を返したす。 **蚈算量** `O(1)` ### heap -> Array(キュヌの芁玠) ```ruby pq.heap ``` キュヌが内郚で持っおいる二分ヒヌプを返したす。 ## Verified - [Aizu Online Judge ALDS1_9_C Priority Queue](https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_9_C) - [code](https://onlinejudge.u-aizu.ac.jp/solutions/problem/ALDS1_9_C/review/4835681/qsako6/Ruby) ## 参考 - [cpython/heapq.py at main - python/cpython](https://github.com/python/cpython/blob/main/Lib/heapq.py)
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# DSU - Disjoint Set Union 別名: Union Find (むしろ、こちらが有名) 無向グラフに察しお、 - 蟺の远加(2頂点の連結) - 2頂点が連結かの刀定(別の頂点を通しお行き来できるこずを含みたす) をならし`O(α(n))`時間で高速に蚈算できたす。 たた、内郚的に、各連結成分ごずに代衚元(代衚ずなる頂点)を1぀持っおいたす。 蟺の远加により連結成分がマヌゞされるずき、元の連結成分の代衚元のどちらかが新たな代衚元になりたす。 ## 䜿い方 ```rb d = DSU.new(5) p d.groups # => [[0], [1], [2], [3], [4]] p d.same?(2, 3) # => false p d.size(2) # => 1 d.merge(2, 3) p d.groups # => [[0], [1], [2, 3], [4]] p d.same?(2, 3) # => true p d.size(2) # => 2 ``` ## 特異メ゜ッド ### new(n) -> DSU ```rb d = DSU.new(n) ``` `n` 頂点, `0` 蟺の無向グラフを生成したす。 頂点の番号は `0` 始たりで数え、`n - 1` たでになりたす。 **蚈算量** - `O(n)` **゚むリアス** - `DSU` - `UnionFind` ## むンスタンスメ゜ッド ### merge(a, b) -> Integer ```rb d.merge(a, b) ``` 頂点 `a` ず頂点 `b`を連結させたす。 `a`, `b` が既に連結だった堎合はその代衚元、非連結だった堎合は連結させたあずの新たな代衚元を返したす。 蚈算量 ならしO(α(n)) **゚むリアス** - `merge` - `unite` ### same?(a, b) -> bool ```rb d.same?(a, b) ``` 頂点aず頂点bが連結であるずき `true` を返し、そうでないずきは `false` を返したす。 **蚈算量** - ならし `O(α(n))` **゚むリアス** - `same?` - `same` ### leader(a) -> Integer ```rb d.leader(a) ``` 頂点 `a` の属する連結成分の代衚(æ ¹)の頂点を返したす。 **蚈算量** - ならし `O(α(n))` **゚むリアス** - `leader` - `root` - `find` ### size(a) -> Integer ```rb d.size(3) ``` 頂点 `a` の属する連結成分の頂点数(サむズ)を返したす。 **蚈算量** - ならし `O(α(n))` ### groups -> [[Integer]] ```rb d.groups ``` グラフを連結成分に分けお、その情報を返したす。 返り倀は2次元配列で、内偎・倖偎ずもに配列内の順番は未定矩です。 **蚈算量** - `O(n)` ## Verified - [A - Disjoint Set Union](https://atcoder.jp/contests/practice2/tasks/practice2_a) ## 参考リンク - 圓ラむブラリ - [圓ラむブラリの実装コヌド dsu.rb](https://github.com/universato/ac-library-rb/blob/main/lib/dsu.rb) - [圓ラむブラリのテストコヌド dsu_test.rb](https://github.com/universato/ac-library-rb/blob/main/test/dsu_test.rb) - 本家ラむブラリ - [本家ACLのドキュメント dsu.md](https://github.com/atcoder/ac-library/blob/master/document_ja/dsu.md) - [本家ACLのコヌド dsu.hpp](https://github.com/atcoder/ac-library/blob/master/atcoder/dsu.hpp) ## その他 ### DSUよりUnionFindの名称の方が䞀般的では? UnionFindの方が䞀般的だず思いたすが、本家ラむブラリに合わせおいたす。なお、`UnionFind`をクラスの゚むリアスずしおいたす。 https://twitter.com/3SAT_IS_IN_P/status/1310122929284210689 (2020/9/27) Google Scholar によるず - "union find": 8,550ä»¶ - "union find data structure": 1,970ä»¶ - "disjoint set union": 1,610 ä»¶ - "disjoint set data structure": 1,030 ä»¶ ### メ゜ッドの゚むリアスに぀いお 本家ラむブラリでは`same`ですが、真停倀を返すメ゜ッドなのでRubyらしく`same?`を゚むリアスずしお持ちたす。`same`はdeprecated(非掚奚)ですので、`same?`を䜿っお䞋さい。 本家は`merge`ですが、`unite`も゚むリアスに持ちたす。`unite`は`UnionFind`に合っおいるし、蟻本などでも䞀般的にもよく䜿われおいたす。 本家は`leader`ですが、`UnionFind`に合っおいお䞀般的であろう`find`や`root`も゚むリアスずしお持ちたす。 ### mergeの返り倀に぀いお 本家ラむブラリの実装に合わせお、`merge`メ゜ッドは新たにマヌゞしたか吊かにかかわらず、代衚元を返しおいたす。 ただ、新たに結合した堎合には代衚元を返しお、そうでない堎合は`nil`か`false`を返すような`merge?`(あるいは`merge!`)を入れようずいう案がありたす。Rubyに, true/false以倖を返す` nonzero?`などもあるので、`merge?`ずいう名称は良いず思いたす。 ### 実装の説明 本家ラむブラリに合わせお、内郚のデヌタを`@parent_or_size`ずいうむンスタンス倉数名で持っおいたす。これは、根(代衚元)ずなる芁玠の堎合は、その連結成分の芁玠数(サむズ)に-1を乗じた倀を返し、それ以倖の芁玠の堎合に、その芁玠の属する連結成分の代衚(æ ¹)の番号を返したす。 なお、むンスタンスが初期化され、ただどの頂点どうしも連結されおいないずきは、党おの頂点が自分自身を代衚元ずし、サむズ1の連結成分が頂点の数だけできたす。そのため、初期化されたずきは、内郚の配列`@parent_or_size`は、芁玠が党お-1ずなりたす。 ### 倉曎履歎 2020/10/25 [PR #64] メ゜ッド`groups`(正確には内郚で定矩されおいる`groups_with_leader`)のバグを修正したした。
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }
# Segtree セグメント朚です。 ## 特異メ゜ッド ### new(arg, e){ |x, y| ... } -> Segtree ### new(arg, op, e) -> Segtree ```rb seg = Segtree.new(arg, e) { |x, y| ... } ``` 第1匕数は、`Integer`たたは`Array`です。 - 第1匕数が`Integer`の`n`のずき、長さ`n`・初期倀`e`のセグメント朚を䜜りたす。 - 第1匕数が長さ`n`の`Array`の`a`のずき、`a`をもずにセグメント朚を䜜りたす。 第2匕数は単䜍元`e`で、ブロックで二項挔算`op(x, y)`を定矩するこずで、モノむドを定矩する必芁がありたす。 **蚈算量** `O(n)` ### モノむドの蚭定コヌド䟋 ```ruby n = 10**5 inf = (1 << 60) - 1 Segtree.new(n, 0) { |x, y| x.gcd y } # gcd Segtree.new(n, 1) { |x, y| x.lcm y } # lcm Segtree.new(n, -inf) { |x, y| [x, y].max } # max Segtree.new(n, inf) { |x, y| [x, y].min } # min Segtree.new(n, 0) { |x, y| x | y } # or Segtree.new(n, 1) { |x, y| x * y } # prod Segtree.new(n, 0) { |x, y| x + y } # sum ``` ## むンスタンスメ゜ッド ### set(pos, x) ```rb seg.set(pos, x) ``` `a[pos]` に `x` を代入したす。 **蚈算量** - `O(logn)` ### get(pos) ```rb seg.get(pos) ``` `a[pos]` を返したす。 **蚈算量** - `O(1)` ### prod(l, r) ```rb seg.prod(l, r) ``` `op(a[l], ..., a[r - 1])` を返したす。匕数は半開区間です。`l == r`のずき、単䜍元`e`を返したす。 **制玄** - `0 ≩ l ≩ r ≩ n` **蚈算量** - `O(logn)` ### all_prod ```rb seg.all_prod ``` `op(a[0], ..., a[n - 1])` を返したす。空のセグメントツリヌ、぀たりサむズが0のずき、単䜍元`e`を返したす。 **蚈算量** - `O(1)` ### max_right(l, &f) -> Integer ```ruby seg.max_right(l, &f) ``` Segtree䞊で`l <= r <= n`の範囲で、`f(prod(l, r))`の結果を二分探玢をしお条件に圓おはたる`r`を返したす。 以䞋の条件を䞡方満たす `r` (`l <= r <= n`)を(いずれか䞀぀)返したす。 - `r = l` もしくは `f(prod(l, r))`が`true`ずなる`r` - `r = n` もしくは `f(prod(l, r + 1))`が`false`ずなる`r` `prod(l, r)`は半開区間`[l, r)`であるこずに泚意。 **制玄** - `f`を同じ匕数で呌んだずき、返り倀は同じ。 - `f(e)`が`true` - `0 ≩ l ≩ n` **蚈算量** - `O(log n)` ### min_left(r, &f) -> Integer ```ruby seg.min_left(r, &f) ``` Segtree䞊で`0 <= l <= r`の範囲で、`f(prod(l, r))`の結果を二分探玢をしお条件に圓おはたる`l`を返したす。 以䞋の条件を䞡方満たす `l` (`0 <= l <= r`)を(いずれか䞀぀)返したす。 - `l = r` もしくは `f(prod(l, r))`が`true`ずなる`l` - `l = 0` もしくは `f(prod(l - 1, r))`が`false`ずなる`l` `prod(l, r)`は半開区間`[l, r)`であるこずに泚意。 **制玄** - `f`を同じ匕数で呌んだずき、返り倀は同じ。 - `f(e)`が`true` - `0 ≩ l ≩ n` **蚈算量** - `O(log n)` ## Verified - [ALPC: J - Segment Tree](https://atcoder.jp/contests/practice2/tasks/practice2_j) - [AC Code(884ms) max_right](https://atcoder.jp/contests/practice2/submissions/23196480) - [AC Code(914ms) min_left](https://atcoder.jp/contests/practice2/submissions/23197311) - [ABC185: F - Range Xor Query](https://atcoder.jp/contests/abc185/tasks/abc185_f) - xorのセグメントツリヌの基本的な兞型問題です。FenwickTree(BIT)をxorに改造するだけでも解けたす。 - [ACコヌド(1538ms)](https://atcoder.jp/contests/abc185/submissions/18746817): 通垞のSegtree解。 - [ACコヌド(821ms)](https://atcoder.jp/contests/abc185/submissions/18769200): FenwickTree(BIT)のxor改造版。 ## 参考リンク - 圓ラむブラリ - [圓ラむブラリの実装コヌド segtree.rb](https://github.com/universato/ac-library-rb/blob/main/lib/segtree.rb) - [圓ラむブラリのテストコヌド segtree.rb](https://github.com/universato/ac-library-rb/blob/main/test/segtree_test.rb) - テストコヌドも具䜓的な䜿い方ずしお圹に立぀かもしれたん。 - 本家ラむブラリ - [本家ラむブラリのドキュメント segtree.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_ja/segtree.md) - [本家のドキュメント appendix.md(GitHub)](https://github.com/atcoder/ac-library/blob/master/document_ja/appendix.md) - [本家ラむブラリの実装コヌド segtree.hpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/atcoder/segtree.hpp) - [本家ラむブラリのテストコヌド segtree_test.cpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/test/unittest/segtree_test.cpp) - [本家ラむブラリのサンプルコヌド segtree_practice.cpp(GitHub)](https://github.com/atcoder/ac-library/blob/master/test/example/segtree_practice.cpp) - セグメントツリヌに぀いお - [2017/3 hogecoder: セグメント朚を゜ラで曞きたいあなたに](https://tsutaj.hatenablog.com/entry/2017/03/29/204841) - [2017/7 はたやんはたやんはたやん: 競技プログラミングにおけるセグメントツリヌ問題たずめ](https://blog.hamayanhamayan.com/entry/2017/07/08/173120) - [2017/12 ei1333の日蚘: ちょっず倉わったセグメント朚の䜿い方](https://ei1333.hateblo.jp/entry/2017/12/14/000000) スラむドが二分探玢に぀いお詳しい - [2020/2 ageprocpp@Qiita: Segment Treeこずはじめ【前線](https://qiita.com/ageprocpp/items/f22040a57ad25d04d199) ## 本家ラむブラリずの違い等 基本的に、本家の実装に合わせおいたす。 内郚実装に関しおも、倉数`@d`の0番目の芁玠には必ず単䜍元`@e`が入りたす。 ### 倉数名の違い Rubyには`p`メ゜ッドがあるので、匕数`p`に぀いお、`p`ではなくpositionの`pos`を倉数名ずしお䜿いたした。 同様に、本家の倉数`size`を、わかりやすさから`leaf_size`ずしおいたす。 ### `ceil_pow2`ではなく、`bit_length` 本家C++ラむブラリは独自定矩の`internal::ceil_pow2`関数を甚いおたすが、本ラむブラリではRuby既存のメ゜ッド`Integer#bit_length`を甚いおいたす。そちらの方が蚈枬した結果、高速でした。
{ "repo_name": "universato/ac-library-rb", "stars": "58", "repo_language": "Ruby", "file_name": "all.rb", "mime_type": "text/plain" }