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.