AcWing 838. 堆排序 - python3
原题链接
简单
作者:
luka_77
,
2020-04-22 17:47:43
,
所有人可见
,
阅读 621
import sys
def down(i):
t = i
if i * 2 <= total and a[t] > a[i << 1]:
t = i * 2
if i * 2 + 1 <= total and a[t] > a[i << 1 | 1]:
t = i * 2 + 1
if t != i:
a[t], a[i] = a[i], a[t]
down(t)
a = []
for line in sys.stdin:
a.append(list(map(int, line.split())))
n, m = a[0][0], a[0][1]
a = [0] + a[1]
total = len(a) - 1
for i in range(total // 2, -1, -1): # 从一半开始倒着往前down
down(i)
while m > 0:
m -= 1
print (a[1], end = " ")
a[1] = a[total]
down(1)
total -= 1