[topic] B+木のノード削除
Posted feedbacks - Flatten
Nested Hidden81 までの自然数をランダムに与えて、さいごまですべて削除できることを確認しました。
see: データベースシステム (後半) - 物理的な格納方式 - B+-Tree
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | | removeNode tree |
removeNode := [:root :elem |
| node branch left middle right target neighbor merged keys
bIndex eIndex path branchOf keysOf fixKeysOf |
root first == #L
ifTrue: [
eIndex := root indexOf: elem.
eIndex = 0 ifTrue: [^nil] ifFalse: [root := root copyWithoutIndex: eIndex]]
ifFalse: [
path := OrderedCollection new.
node := root.
keysOf := [:val | val first == #L ifTrue: [nil] ifFalse: [val second]].
branchOf := [:val | val first == #L ifTrue: [val] ifFalse: [val third]].
fixKeysOf := [:nde |
(keysOf value: nde) ifNotNilDo: [:kys |
kys become: {#K}, (((branchOf value: nde) allButFirst: 2) collect: [:br |
[br first == #L] whileFalse: [br := (branchOf value: br) second].
br second])]].
[ keys := keysOf value: node.
keys ifNil: [target := node] ifNotNil: [
branch := branchOf value: node.
bIndex := keys findLast: [:key | (key isSymbol ifTrue: [0] ifFalse: [key]) <= elem].
bIndex = 0 ifTrue: [^nil].
target := branch at: bIndex + 1].
target first = #L] whileFalse: [path add: node. node := target].
eIndex := target indexOf: elem ifAbsent: [^nil].
target become: (target copyWithoutIndex: eIndex).
(bIndex > 2 and: [eIndex = 2]) ifTrue: [keys at: bIndex put: target second].
[ left := branch second.
middle := branch size > 2 ifTrue: [branch third] ifFalse: [nil].
right := branch size = 4 ifTrue: [branch fourth] ifFalse: [nil].
(branchOf value: target) size = 2 ifTrue: [
neighbor := target caseOf: {[left]->[middle]. [middle]->[left]. [right]->[middle]}.
merged := target == left
ifTrue: [(branchOf value: target), (branchOf value: neighbor) allButFirst]
ifFalse: [(branchOf value: neighbor), (branchOf value: target) allButFirst].
(branchOf value: neighbor) size = 3
ifTrue: [
(branchOf value: neighbor) become: merged.
branch become: (branch copyWithout: target)]
ifFalse: [
target == left ifTrue: [target := neighbor flag: (neighbor := target)].
(branchOf value: target) become: ({target first}, (merged allButFirst: 3)).
fixKeysOf value: target.
(branchOf value: neighbor) become: (merged allButLast: 2)].
fixKeysOf value: neighbor].
fixKeysOf value: node.
branch size = 2 ifFalse: [false] ifTrue: [
path ifEmpty: [node become: branch last. false] ifNotEmpty: [
target := node.
node := path removeLast.
branch := node third.
true]]
] whileTrue].
root].
World findATranscript: nil.
tree := #(N (K 28 55)
(B (N (K 10 19)
(B (N (K 4 7)
(B (L 1 2 3) (L 4 5 6) (L 7 8 9)))
(N (K 13 16)
(B (L 10 11 12) (L 13 14 15) (L 16 17 18)))
(N (K 22 25)
(B (L 19 20 21) (L 22 23 24) (L 25 26 27)))))
(N (K 37 46)
(B (N (K 31 34)
(B (L 28 29 30) (L 31 32 33) (L 34 35 36)))
(N (K 40 43)
(B (L 37 38 39) (L 40 41 42) (L 43 44 45)))
(N (K 49 52)
(B (L 46 47 48) (L 49 50 51) (L 52 53 54)))))
(N (K 64 73)
(B (N (K 58 61)
(B (L 55 56 57) (L 58 59 60) (L 61 62 63)))
(N (K 67 70)
(B (L 64 65 66) (L 67 68 69) (L 70 71 72)))
(N (K 76 79)
(B (L 73 74 75) (L 76 77 78) (L 79 80 81))))))).
(1 to: 81) asArray shuffled do: [:each |
tree := removeNode value: tree value: each.
Transcript cr; show: each asString, ', ', (tree printString copyWithout: $#)]
|
厳密にB+Treeと呼べるのかはわかりませんが それっぽい感じにはなっていると思います。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | class B(list):
def __str__(self):
return '(B %s)' % '\n'.join([str(i) for i in self]).replace('\n', '\n ')
def delete(self, i, k):
if isinstance(self[i], N):
self[i].delete0(k)
if len(self[i].b) < 2:
if i == 0:
if len(self[i+1].b) == 3:
self[i].b.append(self[i+1].b.pop(0))
self[i+1].k = self[i+1].getk()
else:
self[i].b.extend(self[i+1].b)
self.pop(i+1)
self[i].k = self[i].getk()
else:
if len(self[i-1].b) == 3:
self[i].b.insert(0, self[i-1].b.pop())
self[i].k = self[i].getk()
else:
self[i-1].b.extend(self[i].b)
self.pop(i)
self[i-1].k = self[i-1].getk()
else:
self[i].remove(k)
if len(self[i]) < 2:
if i == 0:
if len(self[i+1]) == 3:
self[i].append(self[i+1].pop(0))
else:
self[i].extend(self.pop(i+1))
else:
if len(self[i-1]) == 3:
self[i].insert(0, self[i-1].pop())
else:
self[i-1].extend(self.pop(i))
class L(list):
def __str__(self):
return '(L %s)' % ' '.join(['%2d' % i for i in self])
def delete(self, k):
self.remove(k)
return self
class K(list):
def __str__(self):
return '(K %s)' % ' '.join(['%d' % i for i in self])
class N:
def __init__(self, k=None, b=None):
self.k = k
self.b = b
def __str__(self):
return '(N %s\n %s)' % (self.k, str(self.b).replace('\n', '\n '))
def delete(self, k):
self.delete0(k)
if len(self.b) < 2:
return self.b[0]
return self
def delete0(self, k):
for i, j in enumerate(self.k+[0x100000000]):
if k < j:
self.b.delete(i, k)
self.k = self.getk()
break
def getk(self):
if isinstance(self.b[0], L):
return K([l[0] for l in self.b[1:]])
else:
def getmin(n):
if isinstance(n.b[0], L):
return n.b[0][0]
return getmin(n.b[0])
return K([getmin(n) for n in self.b[1:]])
def mk_data():
r = [N(b=B([L([i, i+1, i+2]) for i in range(j, j+9, 3)])) for j in range(1, 81, 9)]
for i in r:
i.k = i.getk()
r = [N(b=B(r[i*3:i*3+3])) for i in range(3)]
for i in r:
i.k = i.getk()
r = N(b=B(r))
r.k = r.getk()
return r
def test(l):
root = mk_data()
print root, '\n'
for i in l:
root = root.delete(i)
print 'del = %d\n%s\n' % (i, root)
if __name__ == '__main__':
from random import shuffle
test(range(1, 82))
test(range(81, 0, -1))
l = range(1, 82)
shuffle(l)
test(l)
|
CPANのBtrees.pmを使ってお手軽に。 削除ごとのTreeの様子は、YAMLで表示されます。 Dan the CPAN Monger
see: Btrees
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | use strict;
use warnings;
use Btrees;
use YAML::Syck;
my $nodes = shift || 8;
sub comp{ $_[0] <=> $_[1]}
my ($tree, $node);
($tree, $node) = bal_tree_add($tree, $_, \&comp) for (1..$nodes);
for (1..$nodes){
($tree, $node) = bal_tree_del($tree, $_, \&comp);
print YAML::Syck::Dump($tree);
}
|
Rubyで.追加・削除・検索を実装してみました. お題にて示されたデータ構造に対し,ランダムに1~81を削除して最後まで削除できることを確認したほか,ランダムに0~10000の要素を追加したデータ構造を用意し,矛盾なく最後まで削除できることを確認しました.
概要
今回,B+Treeのアルゴリズムを実装したクラスBPlusTreeを作成しました. まず,このクラスの簡単な使い方について説明します.
B+Treeオブジェクトの生成
B+Treeオブジェクト生成の例:
btree = BPlusTree.new
内部節(以下Branch)の持てる分岐の数(最大分岐数)と,葉(以下Leaf)の持てる要素の数は,B+Treeの初期化時に任意の数を設定することができます. この時,各Branchの保持する最小の分岐数は,(最大分岐数 / 2) の切り上げの数となります.最小の要素数についても同様です.
最大分岐数と最大要素数を指定する場合の例:
# Branchの最大分岐数5, Leafの最大要素数3
btree = BPlusTree.new({:maxbranch => 5, :maxentry => 3})
追加・削除・検索
追加・削除・検索の例:
btree = BPlusTree.new
# キーとデータを追加
btree.add(10, "value10")
btree.add(11, "value11")
btree.add(12, "value12")
btree.add(13, "value13")
btree.add(14, "value14")
# 削除
btree.delete(13)
# 検索 (値取得)
pp btree.get(10) # => "value10"
pp btree.get(13) # => nil (要素が無いので)
# 表示
btree.disp # => 以下を表示
# - Branch(root) [(10), 12]
# - Leaf [10, 11]
# - Leaf [12, 14, 15]
btree.disp(true) # => 第一引数により,Leafのデータを表示するか切り替え
# - Branch(root) [(10), 12]
# - Leaf [10:value10, 11:value11]
# - Leaf [12:value12, 14:value14, 15:value15]
# フラットな配列に変換 (全件探索による)
pp btree.to_a # => [[10, "value10"], [11, "value11"],
# [12, "value12"], [14, "value14"], [15, "value15"]
dispメソッドによる表示結果では,Branchの一番目のキーを (...) で括っています.これは「(検索アルゴリズムには影響を及ぼさない)一番目のキーである」程度の控えめな気持ちを表しています.要するに,あまり意味はありません.
その他
ppライブラリ用にpretty_printメソッドを再定義していますので,ppでそれなりに見やすい出力を得ることができます.
pp btreeの出力例:
#<BPlusTree:0x402e7a58
@tree=
#<BPlusTree::BPlusTree:0x402e79cc
@param={:maxbranch=>3, :minentry=>2, :minbranch=>2, :maxentry=>3},
@root=
#<B+T::Branch key:[1, 5] branch:
[#<B+T::Branch key:[1, 3] branch:
[#<B+T::Leaf key:[1, 2] data:["value01", "value02"]>,
#<B+T::Leaf key:[3, 4] data:["value03", "value04"]>]>,
#<B+T::Branch key:[5, 7] branch:
[#<B+T::Leaf key:[5, 6] data:["value05", "value06"]>,
#<B+T::Leaf key:[7, 8, 9] data:["value07", "value08", "value09"]>]>]>>>
new_from_assocクラスメソッド
配列により組み上げた任意の構造から,BPlusTreeオブジェクトを得るために,new_from_assocクラスメソッドを定義しています.これは,本お題を達成する上で必要だったために実装しました.
最初はB+Treeのアルゴリズムを素直に使ってキー1~81を順番に追加してゆき,お題にて提示された構造を作ろうとしましたが,B+Treeの追加アルゴリズムは「追加時に最大要素数(分岐数)以上になった場合,2分割してそれぞれをB+Treeに加える」というものですので,詰め方を工夫しないと充填率100%とはならず,隙間が空いてしまいます.今回は,配列で構造を作った後にB+Treeオブジェクトを組み上げるメソッドを定義して対応しました.
new_from_assocクラスメソッドの使用例:
assoc = [[:branch, [1, 4],
[[:leaf, [1, 2, 3], ["value01", "value02", "value03"]],
[:leaf, [4, 5, 6], ["value04", "value05", "value06"]]]]]
btree = BPlusTree.new_from_assoc(assoc)
btree.disp # => 以下を表示
# - Branch(root) [(1), 4]
# - Leaf [1, 2, 3]
# - Leaf [4, 5, 6]
クラス説明
BPlusTree::BPlusTree
使用者が直接操作するための入り口となるクラスです.add, delete, get, disp, to_aメソッドなどを定義しています.ルートとなるBranchまたはLeafへの参照を保持しています.
また,B+Treeではルートとなるノードについては特別扱いをする必要がありますが,そうした操作も本クラスで実装しています.
BPlusTree::BPlusTree::Node
Leaf, Branchクラスの基底クラスです.共通のメソッドやアクセサメソッドを定義しています.このクラスのインスタンスが作られることはありません.
BPlusTree::BPlusTree::Leaf
Leafのクラスです.add, deleteなど基本的なメソッドを定義しているほか,自身の分割(split)や,兄弟のLeafと要素を配分(balance),兄弟のLeafを自身に併合(integrate)などのメソッドも定義しています.これらのメソッドは,BPlusTree::BranchクラスやBPlusTree::BPlusTreeクラスから呼ばれます.
BPlusTree::BPlusTree::Branch
Branchのクラスです.Leafと同様,Branchの操作に特有なメソッドを定義しています.
BPlusTree
BPlusTree::BPlusTreeクラスのインスタンスを1つだけ保持し,add, delete, get, disp, to_aメソッドを委譲しています.
本来は特に必要ないクラスですが,BPlusTree::BPlusTree.newなどと打つよりBPlusTree.newとできた方が何かと気分がよいために定義してあります.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 | #!/usr/bin/ruby
require 'forwardable'
require 'pp'
#
# BPlusTree class
#
class BPlusTree
extend Forwardable
def_delegators :@tree, :root, :add, :delete, :get, :to_a, :disp
attr_accessor :tree
def initialize(param = {})
@tree = BPlusTree.new(param)
end
def BPlusTree.new_from_assoc(assoc, param = {})
ret = new(param)
ret.tree = BPlusTree.new_from_assoc(assoc, param)
return ret
end
class BPlusTree
attr_accessor :root, :param
def initialize(param = {})
self.param = param
self.root = Leaf.new(self.param)
end
def BPlusTree.new_from_assoc(assoc, param = {})
new(param).create_bptree_from_assoc(assoc)
end
def add(key, value)
ret, _ = self.root.add(key, value)
increase_height if ret == :need_split
return key
end
def delete(key)
ret, di = self.root.delete(key)
if ret == :need_balance and self.root.suitable_root? then
decrease_height
end
return((di.nil?) ? nil : key)
end
def get(key)
self.root.get(key)
end
def to_a
self.root.to_a
end
def disp(with_data = false)
self.root.disp(0, with_data)
end
def create_bptree_from_assoc(assoc)
raise 'Multiple root node occured' if assoc.size > 1
type, key, data = assoc[0]
root = {:leaf => Leaf, :branch => Branch}[type].new_from_assoc(assoc[0])
root.connect_nextp(nil)
self.root = root
return self
end
private
def increase_height
# create a new root
newroot = Branch.new(self.param)
# connect children to new root
lbrother = self.root
bbrother = self.root.split
(newroot.add_child(lbrother).nil? and
newroot.add_child(bbrother).nil?) or
raise("#{self.class}#increase_height: Internal error")
self.root = newroot
end
def decrease_height
self.root = self.root.get_child
end
end
class Node
attr_accessor :key, :param
def initialize(param = {})
self.key = []
self.param = param
@param[:maxentry] ||= 3
@param[:maxbranch] ||= 3
@param[:minentry] ||= (@param[:maxentry] + 1) / 2
@param[:minbranch] ||= (@param[:maxbranch] + 1) / 2
return self
end
def maxentry
@param[:maxentry]
end
def maxbranch
@param[:maxbranch]
end
def minentry
@param[:minentry]
end
def minbranch
@param[:minbranch]
end
def min
return self.key.first
end
protected
def search_insert_pos(key)
for i in 0..self.key.size - 1
return i if key < self.key[i]
end
return self.key.size
end
end
class Leaf < Node
attr_accessor :data, :nextp
def initialize(param = {})
self.data = []
self.nextp = nil
super
end
def Leaf.new_from_assoc(assoc, param = {})
new(param).create_bptree_from_assoc(assoc)
end
def add(key, value)
before = search_insert_pos(key)
self.key[before, 0] = key
self.data[before, 0] = value
ret = nil
ret = :need_split if self.key.size > self.maxentry
return [ret, before]
end
def delete(key)
pos = search_key(key)
return [nil, nil] if pos.nil?
self.key.delete_at(pos)
self.data.delete_at(pos)
ret = nil
ret = :need_balance if self.key.size < self.minentry
return [ret, pos]
end
def get(key)
pos = search_key(key)
return nil if pos.nil?
return self.data[pos]
end
def to_a
ret = self.key.zip(self.data)
return ret if self.nextp.nil?
return ret + self.nextp.to_a
end
def disp(level, with_data = false)
indent = ' ' * level
print indent + '- Leaf' + ((level == 0) ? '(root)' : '') + ' ['
print self.key.zip(self.data).inject('') {|before, (k, d)|
if before.empty? then
k.to_s + (with_data ? ':' + d.to_s : '')
else
before + ', ' + k.to_s + (with_data ? ':' + d.to_s : '')
end
}
puts ']'
end
def pretty_print(pp)
pp.group(1, '#<B+T::Leaf', '>') do
pp.breakable
pp.text('key:')
pp.pp(self.key)
pp.breakable
pp.text('data:')
pp.pp(self.data)
end
end
def split
range = (self.key.size / 2) .. self.key.size - 1
sibling = Leaf.new(self.param)
sibling.key[0, 0] = self.key[range]
sibling.data[0, 0] = self.data[range]
self.key[range] = nil
self.data[range] = nil
sibling.nextp = self.nextp
self.nextp = sibling
return sibling
end
def balance(bigbrother)
if self.key.size + bigbrother.key.size <= self.maxentry then
return :need_integrate
end
if self.key.size + bigbrother.key.size > self.maxentry * 2 then
raise "#{self.class}#balance: Internal error"
end
newkey = self.key.dup + bigbrother.key
newdata = self.data.dup + bigbrother.data
keys = newkey.size
boundary = keys / 2
self.key = newkey[0..boundary-1]
bigbrother.key = newkey[boundary..keys-1]
self.data = newdata[0..boundary-1]
bigbrother.data = newdata[boundary..keys-1]
return nil
end
def integrate(bigbrother)
self.key += bigbrother.key
self.data += bigbrother.data
self.nextp = bigbrother.nextp
bigbrother.nextp = nil
raise "#{self.class}: Internal error" if self.key.size > self.maxentry
return nil
end
def get_child
return self
end
def suitable_root?
return true
end
def create_bptree_from_assoc(assoc)
type, key, data = assoc
unless type == :leaf then
raise "#{self.class}#create_bptree_from_assoc: Internal error"
end
self.key = key
self.data = data
return self
end
def connect_nextp(before = nil)
before.nextp = self unless before.nil?
return self
end
private
def search_key(key)
for i in 0..self.key.size - 1
return i if self.key[i] == key
end
return nil
end
end
class Branch < Node
attr_accessor :branch
def initialize(param = {})
self.branch = []
super
end
def Branch.new_from_assoc(assoc, param = {})
new(param).create_bptree_from_assoc(assoc)
end
def add(key, value)
bi = search_branch(key)
child = self.branch[bi]
ret, before = child.add(key, value)
self.key[bi] = child.key[before] if before == 0
return [nil, bi] if ret.nil?
raise "#{self.class}#add: Internal error" unless ret == :need_split
# split child
bbrother = child.split
ret = self.add_child(bbrother)
return [ret, bi] if ret.nil? or ret == :need_split
raise "#{self.class}#add: Internal error"
end
def delete(key)
bi = search_branch(key)
child = self.branch[bi]
ret, di = child.delete(key)
self.key[bi] = child.key[di] if di == 0
bj = nil
until ret.nil?
case ret
when :need_balance
# choose pair.
bi, bj = self.choose_pair(bi)
lbrother, bbrother = self.branch[bi..bj]
# balance pair
ret = lbrother.balance(bbrother)
self.key[bj] = bbrother.min
when :need_integrate
# remove big-brother
self.branch.delete_at(bj)
self.key.delete_at(bj)
# integrate pair
ret = lbrother.integrate(bbrother)
else
raise "#{self.class}#delete: Internal error"
end
end
ret = nil
ret = :need_balance if self.key.size < self.minbranch
return [ret, bi]
end
def get(key)
bi = search_branch(key)
return self.branch[bi].get(key)
end
def to_a
return self.branch[0].to_a
end
def disp(level, with_data = false)
indent = ' ' * level
puts indent + '- Branch' + (level == 0 ? '(root)' : '') + ' [' +
self.key.inject('') {|before, k|
if before.empty? then
"(#{k})"
else
before + ", #{k}"
end
} + ']'
self.branch.map do |branch|
branch.disp(level + 1, with_data)
end
end
def pretty_print(pp)
pp.group(1) do
pp.text('#<B+T::Branch')
pp.breakable
pp.group(1, 'key:[', ']') do
self.key.inject(false) do |before, key|
pp.comma_breakable if before
pp.pp(key)
true
end
end
pp.breakable
pp.text('branch:')
end
pp.nest(1) do
pp.breakable
pp.group(1, '[', ']') do
self.branch.inject(false) do |before, branch|
pp.comma_breakable if before
pp.pp(branch)
true
end
end
end
pp.text('>')
end
def add_child(child)
before = search_insert_pos(child.min)
self.key[before, 0] = child.min
self.branch[before, 0] = child
return :need_split if self.key.size > self.maxbranch
return nil
end
def split
range = (self.key.size / 2) .. self.key.size - 1
sibling = Branch.new(self.param)
sibling.key[0, 0] = self.key[range]
sibling.branch[0, 0] = self.branch[range]
self.branch[range] = nil
self.key[range] = nil
return sibling
end
def balance(bigbrother)
if self.key.size + bigbrother.key.size <= self.maxbranch then
return :need_integrate
end
if self.key.size + bigbrother.key.size > self.maxbranch * 2 then
raise "#{self.class}#balance: Internal error"
end
# newkeyとnewbranchには,maxbranch * 2個の要素を置くための空間が必要
newkey = self.key.dup + bigbrother.key
newbranch = self.branch.dup + bigbrother.branch
keys = newkey.size
boundary = keys / 2
self.key = newkey[0..boundary-1]
bigbrother.key = newkey[boundary..keys-1]
self.branch = newbranch[0..boundary-1]
bigbrother.branch = newbranch[boundary..keys-1]
return nil
end
def integrate(bigbrother)
for i in 0..bigbrother.key.size - 1
self.add_child(bigbrother.branch[i])
end
raise "#{self.class}: Internal error" if self.key.size > self.maxbranch
return nil
end
def get_child
raise "#{self.class}#get_child: Internal error" if self.key.size != 1
return self.branch[0]
end
def suitable_root?
return true if self.key.size <= 1
return false
end
def choose_pair(lbrother_idx)
lbrother_idx -= 1 if lbrother_idx == self.key.size - 1
bbrother_idx = lbrother_idx + 1
raise "#{self.class}#choose_pair: Internal error" if key.size < 2
return [lbrother_idx, bbrother_idx]
end
def create_bptree_from_assoc(assoc)
type, key, branch = assoc
unless type == :branch then
raise "#{self.class}#create_bptree_from_assoc: Internal error"
end
self.key = key
self.branch = branch.map do |child|
{:leaf => Leaf, :branch => Branch}[child.first].new_from_assoc(child)
end
return self
end
def connect_nextp(before = nil)
self.branch.inject(before) do |before, branch|
branch.connect_nextp(before)
end
end
private
def search_branch(key)
for i in 1..self.key.size - 1
return i - 1 if key < self.key[i]
end
return self.key.size - 1
end
end
end
###########################################################################
# deleting test
puts '[Delete test 1]'
puts
assoc =
[[:branch, [1, 28, 55],
[[:branch, [1, 10, 19],
[[:branch, [1, 4, 7],
[[:leaf, [1, 2, 3], ["data01", "data02", "data03"]],
[:leaf, [4, 5, 6], ["data04", "data05", "data06"]],
[:leaf, [7, 8, 9], ["data07", "data08", "data09"]]]],
[:branch, [10, 13, 16],
[[:leaf, [10, 11, 12], ["data10", "data11", "data12"]],
[:leaf, [13, 14, 15], ["data13", "data14", "data15"]],
[:leaf, [16, 17, 18], ["data16", "data17", "data18"]]]],
[:branch, [19, 22, 25],
[[:leaf, [19, 20, 21], ["data19", "data20", "data21"]],
[:leaf, [22, 23, 24], ["data22", "data23", "data24"]],
[:leaf, [25, 26, 27], ["data25", "data26", "data27"]]]]]],
[:branch, [28, 37, 46],
[[:branch, [28, 31, 34],
[[:leaf, [28, 29, 30] |


moxth #3462() Rating-4/8=-0.50
B+木(B+Tree、B-Plus-Treeなど)とは、B木を拡張した平衡木です。 元のB木は枝や葉に関係なくキーとデータの組が入りますが、 B+木では葉に全てのキーとデータが入り、ルートから葉までの 枝には索引と分岐しか入らず、B木より空間効率が良いアルゴリズムです。 DBなどでよく使われますが、Web上のサンプルとしてはあまり見かけません。 問題: B+木の検索や追加は比較的簡単なので、本題では削除のみに注目します。 B+木のルート(根)とキーを与えると、キーに一致するB+木中の要素を、 要素の順序と木の平衡を保ちながら削除し、更新したB+木を返す関数を 作ってください。(入力するB+木のサンプルは後述します) 条件: ・B+木としては最小のオーダー3の構造を対象にします。 「オーダー3」とは、葉の要素数が2~3、枝の分岐の数も 2~3の範囲を取るものです。(枝の索引数は分岐の数-1) ただしルートのみは、B+木全体の要素の数が3以下の場合、 葉の要素の数が2未満になりえます。(例を見てください) ・要素や索引のキーは数字とし、データは省略してかまいません。 ・B+木そのものやDB以外のライブラリならば使用してかまいません。 ・結果で得られるB+木は入力の複製でもかまいません。(関数型言語への配慮) ・ノードの索引の更新は必ずしも存在する要素のキーと同期させる必要はありません。 ただし検索に支障のない範囲である事。 ・関数に与えたキーがどの要素とも一致せず、削除に失敗する場合は、 NULLなどの生存ノードと区別できる値を返してください。 例: 問題の理解を促すための例示としてB+木をS式のリストで表します。 ※この例の結果と違っていても平衡が保てていればOKです。 リストのタグの意味 … L=葉, N=枝(ノード), B=分岐, K=索引, 数字=キー 例) 1から7までのB+木 (N (K 3 6) ; 検索に使われる索引は、middleとright各々の最小キーがあれば良い (B (L 1 2) ; left (L 3 4 5) ; middle (分岐と葉の数は最小2、最大3つです) (L 6 7))) ; right 1を削除 =>(N (K 4 6) ; middleの最小キーが変化したので索引も更新します (B (L 2 3) ; middleの最小キーをもらって平衡を保ちます (L 4 5) (L 6 7))) さらに2を削除 =>(N (K 6) ; middleの最小キーが変化したので索引も更新します (B (L 3 4 5) ; 不完全なleft(またはmiddle)を削除し統合します (L 6 7))) さらに6を削除 =>(N (K 5) (B (L 3 4) (L 5 7))) さらに4を削除 =>(L 3 5 7) ; 葉の数を保てなくなるので葉のみになります さらに3と5を削除 =>(L 5 7) =>(L 7) ; ルートのみ葉の数が2未満になりえます 入力するB+木のサンプル: 1から81までのB+木を用意しました。 本題はこれらを全て削除して要素数をゼロにできればOKです。 ※S式のリストで出してますが、実際のデータ構造は何でもいいです。 (N (K 28 55) (B (N (K 10 19) (B (N (K 4 7) (B (L 1 2 3) (L 4 5 6) (L 7 8 9))) (N (K 13 16) (B (L 10 11 12) (L 13 14 15) (L 16 17 18))) (N (K 22 25) (B (L 19 20 21) (L 22 23 24) (L 25 26 27))))) (N (K 37 46) (B (N (K 31 34) (B (L 28 29 30) (L 31 32 33) (L 34 35 36))) (N (K 40 43) (B (L 37 38 39) (L 40 41 42) (L 43 44 45))) (N (K 49 52) (B (L 46 47 48) (L 49 50 51) (L 52 53 54))))) (N (K 64 73) (B (N (K 58 61) (B (L 55 56 57) (L 58 59 60) (L 61 62 63))) (N (K 67 70) (B (L 64 65 66) (L 67 68 69) (L 70 71 72))) (N (K 76 79) (B (L 73 74 75) (L 76 77 78) (L 79 80 81)))))))[ reply ]