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"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.