Created
November 16, 2018 08:02
-
-
Save ser1zw/b6b6a973b28c99742cc15f92541800fa to your computer and use it in GitHub Desktop.
Priority Queueの練習
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Priority Queueの練習 | |
# | |
# 参考 | |
# - https://ufcpp.net/study/algorithm/col_heap.html | |
class PriorityQueue | |
attr_reader :data, :test_function | |
def initialize(test_function = ->(a, b) { a <=> b }) | |
@data = [] | |
@test_function = test_function | |
end | |
def push(value) | |
insert(value) | |
end | |
alias_method :<<, :push | |
def append(array) | |
array.each { |value| insert(value) } | |
end | |
def shift | |
ret = @data[0] | |
@data[0] = @data.last | |
@data.pop | |
make_heap | |
ret | |
end | |
def first | |
@data[0] | |
end | |
def size | |
@data.size | |
end | |
private | |
def insert(value) | |
@data << value | |
i = @data.size - 1 | |
while (i > 0) | |
parent = ((i - 1) / 2).floor | |
break unless test_function.call(@data[parent], @data[i]) < 0 | |
@data[parent], @data[i] = @data[i], @data[parent] | |
i = parent | |
end | |
end | |
def make_heap | |
parent = 0 | |
loop { | |
child = 2 * parent + 1 | |
break unless child < @data.size | |
child += 1 if child < @data.size - 1 and (test_function.call(@data[child], @data[child + 1]) < 0) | |
if test_function.call(@data[parent], @data[child]) < 0 | |
@data[parent], @data[child] = @data[child], @data[parent] | |
end | |
parent = child | |
} | |
end | |
end | |
queue = PriorityQueue.new | |
queue << 3 | |
queue << 1 | |
queue << 4 | |
queue.append([1, 5, 9, 2]) | |
puts "Max: #{queue.first}" | |
pp Array.new(queue.size) { queue.shift } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment