L2-012 关于堆的判断

L2-012 关于堆的判断 ,第1张

L2-012 关于堆的判断 (25 分) Python 题目描述:

思路:

主要学习一下堆的思路。

  1. 父节点pos = (pos - 1) // 2
  2. 左孩子pos = pos * 2 + 1
  3. 右孩子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')

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/717601.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-25
下一篇2022-04-25

发表评论

登录后才能评论

评论列表(0条)

    保存