Pagini recente » Cod sursa (job #486474) | Cod sursa (job #2401386) | Cod sursa (job #632196) | Rating volanschi matei (mateivolanschi) | Cod sursa (job #3140843)
class BinomialHeapNode:
def __init__(self, value):
self.value = value
self.rank = 0
self.children = []
def __lt__(self, other):
return self.value < other.value
class BinomialHeap:
def __init__(self):
self.trees = []
def insert(self, value):
node = BinomialHeapNode(value)
heap = BinomialHeap()
heap.trees.append(node)
self.merge(heap)
def merge(self, other):
self.trees.extend(other.trees)
self.trees.sort(key=lambda x: x.rank)
self._combine_trees()
def _combine_trees(self):
i = 0
while i < len(self.trees) - 1:
current_tree = self.trees[i]
next_tree = self.trees[i + 1]
if current_tree.rank == next_tree.rank:
if current_tree < next_tree:
current_tree.children.append(next_tree)
else:
next_tree.children.append(current_tree)
del self.trees[i + 1]
i += 1
def get_max(self):
if len(self.trees) == 0:
return None
max_node = max(self.trees)
return max_node.value
def extract_max(self):
if len(self.trees) == 0:
return None
max_node = max(self.trees)
self.trees.remove(max_node)
new_heap = BinomialHeap()
new_heap.trees.extend(reversed(max_node.children))
self.merge(new_heap)
return max_node.value
with open("mergeheap.in", "r") as input_file, open("mergeheap.out", "w") as output_file:
N, Q = map(int, input_file.readline().split())
heaps = [BinomialHeap() for _ in range(N)]
for _ in range(Q):
operation = list(map(int, input_file.readline().split()))
if operation[0] == 1:
x = operation[2]
heap_idx = operation[1] - 1
if heap_idx < N:
heaps[heap_idx].insert(x)
elif operation[0] == 2:
heap_idx = operation[1] - 1
if heap_idx < N:
max_element = heaps[heap_idx].extract_max()
if max_element is not None:
output_file.write(str(max_element) + "\n")
elif operation[0] == 3:
heap_idx_a = operation[1] - 1
heap_idx_b = operation[2] - 1
if heap_idx_a < N and heap_idx_b < N:
heaps[heap_idx_a].merge(heaps[heap_idx_b])