-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek2.4.py
More file actions
232 lines (201 loc) · 7.96 KB
/
Copy pathweek2.4.py
File metadata and controls
232 lines (201 loc) · 7.96 KB
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
# N = int(input())
# order = map(int, input().split(' '))
# # Класс для Левой кучи (Максимальной) - ручная реализация
# class MaxHeap:
# def __init__(self):
# self.data = []
# self.size = 0 # Обычная переменная
# def get_max(self):
# # В корне всегда находится элемент с максимальным ключом
# if self.size == 0:
# return -float('inf')
# return self.data[0]
# def insert(self, val):
# # MAX-HEAP-INSERT: Добавляем в конец и поднимаем вверх
# self.data.append(val)
# self.size += 1
# self._sift_up(self.size - 1)
# def extract(self):
# # HEAP-EXTRACT-MAX: Меняем корень с последним, удаляем и чиним
# if self.size == 0:
# return None
# max_val = self.data[0]
# last_val = self.data.pop()
# self.size -= 1
# if self.size > 0:
# self.data[0] = last_val
# self._sift_down(0) # MAX-HEAPIFY
# return max_val
# def _sift_up(self, idx):
# # Поднимаем элемент, пока он больше родителя
# while idx > 0:
# parent = (idx - 1) // 2 # Индекс родителя
# if self.data[idx] > self.data[parent]:
# self.data[idx], self.data[parent] = self.data[parent], self.data[idx]
# idx = parent
# else:
# break
# def _sift_down(self, idx):
# # Опускаем элемент (MAX-HEAPIFY)
# while True:
# left = 2 * idx + 1 # Левый потомок
# right = 2 * idx + 2 # Правый потомок
# largest = idx
# if left < self.size and self.data[left] > self.data[largest]:
# largest = left
# if right < self.size and self.data[right] > self.data[largest]:
# largest = right
# if largest != idx:
# self.data[idx], self.data[largest] = self.data[largest], self.data[idx]
# idx = largest
# else:
# break
# # Класс для Правой кучи (Минимальной) - ручная реализация
# class MinHeap:
# def __init__(self):
# self.data = []
# self.size = 0
# def get_min(self):
# if self.size == 0:
# return float('inf')
# return self.data[0]
# def insert(self, val):
# self.data.append(val)
# self.size += 1
# self._sift_up(self.size - 1)
# def extract(self):
# if self.size == 0:
# return None
# min_val = self.data[0]
# last_val = self.data.pop()
# self.size -= 1
# if self.size > 0:
# self.data[0] = last_val
# self._sift_down(0)
# return min_val
# def _sift_up(self, idx):
# while idx > 0:
# parent = (idx - 1) // 2
# if self.data[idx] < self.data[parent]: # МЕНЬШЕ родителя
# self.data[idx], self.data[parent] = self.data[parent], self.data[idx]
# idx = parent
# else:
# break
# def _sift_down(self, idx):
# while True:
# left = 2 * idx + 1
# right = 2 * idx + 2
# smallest = idx
# if left < self.size and self.data[left] < self.data[smallest]: # Ищем МЕНЬШЕГО
# smallest = left
# if right < self.size and self.data[right] < self.data[smallest]:
# smallest = right
# if smallest != idx:
# self.data[idx], self.data[smallest] = self.data[smallest], self.data[idx]
# idx = smallest
# else:
# break
# max_heap_left = MaxHeap()
# min_heap_right = MinHeap()
# for item_order in order:
# if max_heap_left.size == 0 or item_order < max_heap_left.get_max():
# max_heap_left.insert(item_order)
# else:
# min_heap_right.insert(item_order)
# # балансировка - Если слева элементов больше чем (справа + 1), перекидываем вправо
# if max_heap_left.size > min_heap_right.size + 1:
# move_item = max_heap_left.extract()
# min_heap_right.insert(move_item)
# elif min_heap_right.size > max_heap_left.size:
# move_item = min_heap_right.extract()
# max_heap_left.insert(move_item)
# total = max_heap_left.size + min_heap_right.size
# if total % 2 != 0:
# print(max_heap_left.get_max())
# else:
# # Для четного кол-ва берем среднее значение вершин двух куч
# val = (max_heap_left.get_max() + min_heap_right.get_min()) // 2
# print(val)
# 1. Сначала объявляем класс
class MinHeap:
def __init__(self):
self.data = []
self.size = 0
def insert(self, val):
self.data.append(val)
self.size += 1
self._sift_up(self.size - 1)
def extract(self):
if self.size == 0:
return None
min_val = self.data[0]
last_val = self.data.pop()
self.size -= 1
if self.size > 0:
self.data[0] = last_val
self._sift_down(0)
return min_val
def _sift_up(self, idx):
while idx > 0:
parent = (idx - 1) // 2
# Сравниваем кортежи (priority, name)
if self.data[idx] < self.data[parent]:
self.data[idx], self.data[parent] = self.data[parent], self.data[idx]
idx = parent
else:
break
def _sift_down(self, idx):
while True:
left = 2 * idx + 1
right = 2 * idx + 2
smallest = idx
if left < self.size and self.data[left] < self.data[smallest]:
smallest = left
if right < self.size and self.data[right] < self.data[smallest]:
smallest = right
if smallest != idx:
self.data[idx], self.data[smallest] = self.data[smallest], self.data[idx]
idx = smallest
else:
break
N = int(input())
groups = {}
output = []
for _ in range(N):
parts = input().split()
cmd = parts[0]
if cmd == "create":
group_id = int(parts[1])
groups[group_id] = MinHeap()
elif cmd == "add":
s = parts[1]
x = int(parts[2])
y = int(parts[3])
groups[y].insert((x, s))
elif cmd == "execute":
group_id = int(parts[1])
if group_id in groups:
res = groups[group_id].extract()
if res:
priority, name = res
output.append(f"{name} {priority}")
elif cmd == "merge":
x = int(parts[1])
y = int(parts[2])
z = int(parts[3])
# Извлекаем кучи. Используем .get() или pop() аккуратно
# (по условию задачи x и y гарантированно существуют)
heap_a = groups.pop(x)
heap_b = groups.pop(y)
# Эвристика Small-to-Large
if heap_a.size < heap_b.size:
target_heap = heap_b
source_heap = heap_a
else:
target_heap = heap_a
source_heap = heap_b
# Переносим элементы
for item in source_heap.data:
target_heap.insert(item)
groups[z] = target_heap
print('\n'.join(output))