差分
このページの2つのバージョン間の差分を表示します。
両方とも前のリビジョン前のリビジョン次のリビジョン | 前のリビジョン次のリビジョン両方とも次のリビジョン | ||
programming_algorithm:data_structure:binary_indexed_tree [2020/12/13] – [より柔軟な実装] ikatakos | programming_algorithm:data_structure:binary_indexed_tree [2020/12/13] – [累積和の二分探索] ikatakos | ||
---|---|---|---|
行 90: | 行 90: | ||
self.func = func | self.func = func | ||
self.idf = identity_factory | self.idf = identity_factory | ||
- | self.depth = n.bit_length() | ||
def add(self, i, x): | def add(self, i, x): | ||
行 108: | 行 107: | ||
return s | return s | ||
- | def lower_bound(self, | ||
- | """ | ||
- | 累積和がx以上になる最小のindexと、その直前までの累積和(未検証) | ||
- | |||
- | :param lt: lt(a, b) で a < b ならTrueを返す関数 | ||
- | """ | ||
- | total = self.idf() | ||
- | pos = 0 | ||
- | tree = self.tree | ||
- | func = self.func | ||
- | for i in range(self.depth, | ||
- | k = pos + (1 << i) | ||
- | new_total = func(total, tree[k]) | ||
- | if k <= self.size and lt(new_total, | ||
- | total = new_total | ||
- | pos += 1 << i | ||
- | return pos + 1, total | ||
</ | </ | ||
行 276: | 行 258: | ||
</ | </ | ||
+ | |||
+ | ++++ Injectable版 | | ||
+ | |||
+ | <sxh python> | ||
+ | class FenwickTreeInjectable: | ||
+ | def __init__(self, | ||
+ | self.size = n | ||
+ | self.tree = [identity_factory() for _ in range(n + 1)] | ||
+ | self.func = func | ||
+ | self.idf = identity_factory | ||
+ | self.depth = n.bit_length() | ||
+ | |||
+ | def add(self, i, x): | ||
+ | tree = self.tree | ||
+ | func = self.func | ||
+ | while i <= self.size: | ||
+ | tree[i] = func(tree[i], | ||
+ | i += i & -i | ||
+ | |||
+ | def sum(self, i): | ||
+ | s = self.idf() | ||
+ | tree = self.tree | ||
+ | func = self.func | ||
+ | while i > 0: | ||
+ | s = func(s, tree[i]) | ||
+ | i -= i & -i | ||
+ | return s | ||
+ | |||
+ | def lower_bound(self, | ||
+ | """ | ||
+ | 累積和がx以上になる最小のindexと、その直前までの累積和(未検証) | ||
+ | |||
+ | :param lt: lt(a, b) で a < b ならTrueを返す関数 | ||
+ | """ | ||
+ | total = self.idf() | ||
+ | pos = 0 | ||
+ | tree = self.tree | ||
+ | func = self.func | ||
+ | for i in range(self.depth, | ||
+ | k = pos + (1 << i) | ||
+ | new_total = func(total, tree[k]) | ||
+ | if k <= self.size and lt(new_total, | ||
+ | total = new_total | ||
+ | pos += 1 << i | ||
+ | return pos + 1, total | ||
+ | </ | ||
+ | |||
+ | ++++ | ||