AcWing 1588. 插入还是堆排序
原题链接
中等
作者:
aac
,
2024-11-23 15:33:04
,
所有人可见
,
阅读 1
def down(u):
t = u
if 2 * u <= k - 1 and b[2 * u] > b[t]: # 注意一定是2 * u <= k - 1,而不是2 * u <= n,k - 1是现在堆尾所在元素的下标,而不是n
t = 2 * u
if 2 * u + 1 <= k - 1 and b[2 * u + 1] > b[t]: # 注意一定是2 * u + 1 <= k - 1,而不是2 * u + 1 <= n,k - 1是现在堆尾所在元素的下标,而不是n
t = 2 * u + 1
if t != u:
b[t], b[u] = b[u], b[t]
down(t)
N = 110
a = [0] * N
b = [0] * N
n = int(input())
for i, x in enumerate(list(map(int, input().split())), start=1):
a[i] = x
for i, x in enumerate(list(map(int, input().split())), start=1):
b[i] = x
i = 1
while i <= n and b[i - 1] <= b[i]: # 一定是小于等于号,而不是小于号,注意
i += 1
flag = True
t = i
for i in range(t, n + 1):
if a[i] != b[i]:
flag = False
break
if flag:
print("Insertion Sort")
while t - 1 >= 1 and b[t - 1] > b[t]:
b[t - 1], b[t] = b[t], b[t - 1]
t -= 1
else:
k = n
while k > 1 and b[k] >= b[1]:
k -= 1
b[1], b[k] = b[k], b[1]
down(1)
print("Heap Sort")
ans = [str(x) for x in b[1:n + 1]]
print(" ".join(ans))