L2-012 关于堆的判断 (25 分) Python
题目描述:
思路:
主要学习一下堆的思路。
- 父节点pos = (pos - 1) // 2
- 左孩子pos = pos * 2 + 1
- 右孩子pos = pos * 2 + 2
AC代码
def checkHeap(heap, target):
if target == 0:
return heap
if heap[target] < heap[(target - 1) // 2]:
temp = heap[target]
heap[target] = heap[(target - 1) // 2]
heap[(target - 1) // 2] = temp
heap = checkHeap(heap, (target - 1) // 2)
return heap
def heapInsert(heap, value, _index):
heap[_index] = value
return checkHeap(heap, _index)
n, m = map(int, input().split())
heap = [None for i in range(n)]
values = list(map(int, input().split()))
for i, item in enumerate(values):
heap = heapInsert(heap, item, i)
for i in range(m):
command_words = input().split()
if 'root' in command_words:
print('T') if heap[0] == int(command_words[0]) else print('F')
elif 'siblings' in command_words:
print('T') if ((heap.index(int(command_words[0])) - 1) // 2) == ((heap.index(int(command_words[2])) - 1) // 2) else print('F')
elif 'parent' in command_words:
print('T') if heap.index(int(command_words[0])) == ((heap.index(int(command_words[-1])) - 1) // 2) else print('F')
else:
print('T') if heap.index(int(command_words[-1])) == (heap.index(int(command_words[0])) - 1) // 2 else print('F')