Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for array as argument to FenwickTree#new #1

Merged
merged 1 commit into from
May 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ For the convinience of usage in programming contest, each class in the library d
## [FenwickTree.cr](atcoder/FenwickTree.cr) ([<atcoder/fenwicktree>](https://atcoder.github.io/ac-library/document_en/fenwicktree.html))

* `fenwick_tree<T> fw(n)` => `AtCoder::FenwickTree(T).new(n)`
* `fenwick_tree<T> fw(array)` => `AtCoder::FenwickTree(T).new(array)`

```cr
tree = AtCoder::FenwickTree(Int64).new(10)
Expand Down
15 changes: 13 additions & 2 deletions atcoder/FenwickTree.cr
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,21 @@ module AtCoder
getter size : Int64
getter bits : Array(T)

def initialize(@size)
def initialize(@size : Int64)
@bits = Array(T).new(@size, T.zero)
end

def initialize(@bits : Array)
@bits = @bits.dup
@size = @bits.size.to_i64
(1 ... @size).each do |index|
up = index + (index & -index)
next if up > @size

@bits[up - 1] += @bits[index - 1]
end
end

# Implements atcoder::fenwick_tree.add(index, value)
def add(index, value)
index += 1 # convert to 1-indexed
Expand Down Expand Up @@ -63,4 +74,4 @@ module AtCoder
sum(left, right)
end
end
end
end
12 changes: 12 additions & 0 deletions spec/atcoder/FenwickTree_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,18 @@ require "spec"
alias FenwickTree = AtCoder::FenwickTree

describe "FenwickTree" do
describe "#new(array)" do
it "equals #new(int64)" do
a = [10, 20, 30, 40, 50, 60, 70].map(&.to_i64)
tree1 = FenwickTree(Int64).new(a)
tree2 = FenwickTree(Int64).new(a.size.to_i64)
a.each_with_index{ |e, i| tree2.add(i, e) }

tree1.size.should eq tree2.size
tree1.bits.should eq tree2.bits
end
end

describe "#left_sum" do
it "calculates left_sum of given list" do
tree = FenwickTree(Int64).new(11_i64)
Expand Down