AcWing 838. 堆排序 python
原题链接
简单
作者:
申侠
,
2020-10-22 19:43:04
,
所有人可见
,
阅读 283
class Heap(object):
def __init__(self, m):
self.lt = m
self.size = len(m) - 1
self.sort()
def pop(self):
r = self.lt[1]
self.lt[1] = self.lt[self.size]
self.size -= 1
self.down(1)
return r
def down(self, u):
t = u
if 2*u <= self.size and self.lt[t] > self.lt[2*u]:
t = 2 * u
if 2*u+1 <= self.size and self.lt[t] > self.lt[2*u+1]:
t = 2 *u + 1
if t != u:
self.lt[t], self.lt[u] = self.lt[u], self.lt[t]
self.down(t)
def sort(self):
for i in range(int(self.size/2),0,-1):
self.down(i)
n,m = map(int, input().split(' '))
t = [0]
t.extend(list(map(int, input().split(' '))))
h = Heap(t)
o = map(str, [h.pop() for _ in range(m)])
print(' '.join(o))