This theme, priority queue
Problems such as the advanced version of * Solved in Ruby, Python and Java AtCoder ABC141 D Priority Queuing *.
Queues the maximum and second maximum of a given array, subtracts 1 and puts it back in the queue. This is repeated until the queue is filled with one or less, and the loop is exited.
There is also a mathematical solution.
ruby.rb
k = gets.to_i
a = gets.split.map(&:to_i).max
puts [0, 2 * a - k - 1].max
I will pay attention to the maximum value and solve it, but the refreshing feeling is amazing. Ruby Heap
ruby.rb
class Heap
attr_reader :size
def initialize(up: false)
@up = up
@heap = []
@size = 0
end
def sum
x = 0
@size.times do |i|
x += @heap[i]
end
x
end
def push(n)
n = -n if @up
i = @size
while i > 0
pid = (i - 1) / 2
break if n >= @heap[pid]
@heap[i] = @heap[pid]
i = pid
end
@heap[i] = n
@size += 1
end
def pop
return nil if @size == 0
top = @heap[0]
@size -= 1
n = @heap[@size]
i = 0
while i * 2 + 1 < @size
cid1 = i * 2 + 1
cid2 = cid1 + 1
if cid2 < @size && @heap[cid2] < @heap[cid1]
cid1 = cid2
end
break if @heap[cid1] >= n
@heap[i] = @heap[cid1]
i = cid1
end
@heap[i] = n
if @up
-top
else
top
end
end
end
gets
a = gets.split.map(&:to_i)
h = Heap.new(up: true)
a.each do |x|
h.push(x)
end
while h.size > 1
u = h.pop
v = h.pop
h.push(u - 1) if u - 1 > 0
h.push(v - 1) if v - 1 > 0
end
if h.size == 0
puts "0"
else
puts h.pop - 1
end
up.rb
def initialize(up: false)
@up = up
heap.rb
while h.size > 1
u = h.pop
v = h.pop
h.push(u - 1) if u - 1 > 0
h.push(v - 1) if v - 1 > 0
end
Take two, subtract them, and if they are 1 or more, put them back in the queue.
python.py
from sys import stdin
def main():
input = stdin.readline
k, _ = map(int, input().split())
a = max(map(int, input().split()))
print(max(0, 2 * a - k - 1))
main()
Python heapq
python.py
from sys import stdin
def main():
import heapq
input = stdin.readline
input()
a = [-1 * int(i) for i in input().split()]
heapq.heapify(a)
while len(a) > 1:
u = heapq.heappop(a)
v = heapq.heappop(a)
if u + 1 < 0:
heapq.heappush(a, u + 1)
if v + 1 < 0:
heapq.heappush(a, v + 1)
if len(a) == 0:
print(0)
else:
print(abs(a[0] + 1))
main()
If the operation is complicated, it is better to prepare a function for code conversion.
Ruby mathematical solution | Ruby Heap | Python mathematical solution | Python heapq | |
---|---|---|---|---|
Code length(Byte) | 76 | 1120 | 184 | 458 |
Execution time(ms) | 7 | 26 | 17 | 22 |
memory(KB) | 1788 | 1788 | 2940 | 3064 |
Referenced site
Recommended Posts