差分
このページの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): | ||
行 106: | 行 107: | ||
i -= i & -i | i -= i & -i | ||
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 | ||
</ | </ | ||
listやdictなどのオブジェクトを載せることもできる。\\ | listやdictなどのオブジェクトを載せることもできる。\\ | ||
- | Pythonでは、オブジェクトを特に工夫無くコピーするとインスタンス自体が同じとなる。つまりどれか1つへの反映が他の全てに反映されてしまう。 | + | その場合の注意点として、Pythonでは、オブジェクトを特に工夫無くコピーするとインスタンス自体が同じとなる。つまりどれか1つへの反映が他の全てに反映されてしまう。 |
それを防ぐため、'' | それを防ぐため、'' | ||
- | <sxh python> | + | <sxh python; |
- | # だめな例 | + | |
a = [0, 0] | a = [0, 0] | ||
aaa = [a] * 3 | aaa = [a] * 3 |