We need to write a program that reads H and the array (1-indexed) and constructs a max-heap by applying buildMaxHeap. Then output the resulting array values with a space before each value? The problem says: "Print a single space character before each value." That means output format: " 16 14 10 8 7 9 3 2 4 1"? Actually they have output "16 14 10 8 7 9 3 2 4 1" in the example. But they said "Print a single space character before each value." That could be interpreted as output like " 16 14 10 8 7 9 3 2 4 1" with a leading space. But typical output does not require a leading space. However to be safe, we can print the values separated by spaces, and maybe start with a space? Let's check example: Input: 10 and numbers. Output: "16 14 10 8 7 9 3 2 4 1". Typically no leading space. But the statement might be a translation artifact. In many problems like from AOJ (AIZU), they ask to print a space before each value, meaning between values there is a space, and maybe before the first? But that would cause a leading space. Usually they want a space between values. Let's see: "Print a single space character before each value." Could be interpreted as "Print a space before each value except the first"? But they didn't specify. Usually they say "print values separated by a single space" not "before each". In some problems, they require "print a space before each value" meaning you print a space and then the value, but then the output starts with a space. In the sample output, they show "16 14 10 8 7 9 3 2 4 1". That has no leading space. So maybe they mean "print a space between values". I'll assume standard: print values separated by spaces, no leading/trailing spaces. But to be safe, we could print like: for i in range(1, H+1): print((" " if i>1 else "") + str(A[i]), end="") then newline. Many solutions just print with join.
Now the main task: implement buildMaxHeap and maxHeapify. Input H up to? Possibly up to 500,000? But can be straightforward.
We need to use 1-indexed array. Typically we read H, then the list of H numbers. We can store them in a list with index 0 as dummy and then index 1..H.
Implementation: Define functions left(i)=2i, right(i)=2i+1.
We need to run for i from floor(H/2) down to 1: maxHeapify(A, i).
Then output A[1..H] with spaces.
Let's test with example: H=10, A: [4,1,3,2,16,9,10,14,8,7] after building max-heap should become [16,14,10,8,7,9,3,2,4,1] indeed.
We'll implement maxHeapify iteratively? Recursively is fine given constraints but we can also implement iteratively to avoid recursion depth if H large (like 500k recursion depth might be up to log2(500k) ~ 19, fine). But we can also use recursion.
So plan:
- Read H.
- Read the list of H integers, maybe input split.
- Insert dummy at front: A = [0] + list_of_ints.
- Define functions.
Pseudo:
def max_heapify(A, i):
H = len(A)-1
l = 2i
r = 2i+1
largest = i
if l <= H and A[l] > A[largest]:
largest = l
if r <= H and A[r] > A[largest]:
largest = r
if largest != i:
A[i], A[largest] = A[largest], A[i]
max_heapify(A, largest)
But careful: H should be the heap size; we need to pass H as parameter or use global variable? The pseudo-code uses H as heap size, which is constant. In Python, we can use len(A)-1 or a global variable. Since H is given and we won't change the size, we can just compute within function. But note that max_heapify might be called recursively; the heap size does not change. So we can use the length of A - 1.
Alternatively, we could pass H as parameter.
But note: In buildMaxHeap, we need H as size. So we can define H = len(A)-1.
Thus:
def build_max_heap(A):
H = len(A)-1
for i in range(H//2, 0, -1):
max_heapify(A, i)
Then after building, print.
Edge Cases: H=0? Possibly not, H given as integer, maybe >=1. We'll assume at least 1.
Complexity: O(H).
Now about input: multiple lines? Possibly all numbers in one line. Use sys.stdin.read() to read all and split.
Now confirm output format: The problem statement says: "Print values of nodes in the max-heap in order of their id (from 1 to H). Print a single space character before each value." In the example output, they show "16 14 10 8 7 9 3 2 4 1". That doesn't have a leading space. Maybe they consider printing a space before each value means there is a space between values, and perhaps they don't mind leading? Usually they want exactly as shown. So I'll output as: print(' '.join(map(str, A[1:]))).
But to be precise, I can check typical AOJ problem: "ALDS1_9_B: Maximum Heap" maybe? Indeed this is a typical problem: "Maximum Heap" from ALDS1_9_B. The sample output is " 16 14 10 8 7 9 3 2 4 1"? Wait I recall that problem: "Maximum Heap" from ALDS1 (Aizu) asks to output the built heap with a space before each value, and sample output shows " 16 14 10 8 7 9 3 2 4 1"? Let me check my memory: Actually I've seen the problem: "Maximum Heap" (ALDS1_9_B) requires to output each node with a space before it, including the first? For example, the sample output: " 16 14 10 8 7 9 3 2 4 1". Yes, many solutions produce a leading space. Let's check typical AOJ problem description: "Print the processed sequence (heap) in the format: a space before each key value." And the sample output actually includes a leading space. I'm not 100% sure. But I've solved it before: They require a space before each value, which results in a leading space. For example, on the online judge they might check with exact string, so we need to follow that.
Let's examine the problem statement given here: "Print a single space character before each value." That is explicit: before each value, print a space. So for the first value, before it, there is a space. So output begins with a space. In the example, they show "16 14 10 8 7 9 3 2 4 1". But perhaps they omitted the leading space in the statement for readability, but they intend to have it. Or maybe they used a formatting that doesn't show the leading space. In many PDFs, a leading space might be ignored. Actually the problem statement shows:
Output
16 14 10 8 7 9 3 2 4 1
There is no visible leading space. However they said "Print a single space character before each value." That could be interpreted as "print a space between values", but they said "before each value", which includes the first.
To be safe, we can look for the problem on typical judges. This looks like a problem from AIZU Online Judge (ALDS1_9_B). I recall the exact sample: Input: 10 and numbers. Output: " 16 14 10 8 7 9 3 2 4 1". That is, a space at the beginning. Many Python solutions do: print('', *A[1:])? Actually they do: print('', *A[1:])? That prints a leading space because the separator is a space and the first argument is empty string? Actually print('', *A[1:]) prints a space between the empty string and the first number, resulting in a leading space? Let's test: print('', *A[1:]) in Python prints an empty string then a space (since sep=' ') then the numbers. So output starts with a space? For example: print('', 16, 14) -> " 16 14". Indeed it prints a space then 16 then space then 14. So many solutions use that.
Alternatively, we can build a string: ' ' + ' '.join(map(str, A[1:])) which yields leading space. I'll do that to be safe.
So final output: print(' ' + ' '.join(map(str, A[1:])))
But careful: if H=0? not needed.
Now let's code.
We should also consider that the maxHeapify procedure expects the heap size H as a parameter? In the pseudo-code, they have H as global. But we can just use the length.
Implementation steps:
import sys
def main():
data = sys.stdin.read().split()
if not data: return
H = int(data[0])
A = [0] + list(map(int, data[1:1+H]))
# Build max heap
def max_heapify(i):
nonlocal A
l = 2i
r = 2i+1
largest = i
if l <= H and A[l] > A[largest]:
largest = l
if r <= H and A[r] > A[largest]:
largest = r
if largest != i:
A[i], A[largest] = A[largest], A[i]
max_heapify(largest)
# Note: H is unchanged; we need to capture H from outer scope. Use nonlocal H? But H is immutable so we can just use the variable from outer scope. Since it's not reassigned, it's fine.
for i in range(H//2, 0, -1):
max_heapify(i)
# Output with leading space
print(' ' + ' '.join(map(str, A[1:])))
if name == "main":
main()
But the max_heapify function defined inside uses H from outer scope; that's fine.
However, note that H is the original size, but after swaps we don't change H. So good.
But we need to ensure recursion depth; H may be up to 500,000, but recursion depth is at most the height of the tree, which is about log2(H) ~ 19, safe.
We'll also test with given example: Should produce " 16 14 10 8 7 9 3 2 4 1". We'll also consider that the output may need a newline at the end; print adds newline.
Alternatively, we could implement iteratively.
Also note: The pseudo-code uses H as heap size. Our max_heapify uses H from outer scope. But inside max_heapify we might want to pass H as argument? Not needed.
Now confirm correctness:
Start: A = [0,4,1,3,2,16,9,10,14,8,7]; H=10.
Loop i from 5 to 1:
i=5: max_heapify(5) -> l=10, r=11>10 -> compare A[5]=16, A[10]=7 => largest=5; so nothing.
i=4: l=8,r=9; A[4]=2, A[8]=14 => largest=8; swap A[4]=14, A[8]=2; call max_heapify(8) -> l=16>10, r=17>10 => largest=8; so nothing else. Now A: [0,4,1,3,14,16,9,10,2,8,7]
i=3: l=6,r=7; A[3]=3, A[6]=9 => largest=6; swap A[3]=9, A[6]=3; call max_heapify(6) -> l=12>10, r=13>10; largest=6; no further. Now A: [0,4,1,9,14,16,3,10,2,8,7]
i=2: l=4,r=5; A[2]=1, A[4]=14 => largest=4; swap A[2]=14, A[4]=1; call max_heapify(4) -> l=8,r=9; A[4]=1, A[8]=2, A[9]=8 => largest=9 (since 8>1 and 8>2? Actually A[9]=8, compare: l=8:2, r=9:8, largest initially 4=1, then l:2>1 -> largest=8 (value 2), then r:8 >2 -> largest=9). So swap A[4]=8, A[9]=1; call max_heapify(9) -> l=18>10, r=19>10; stop. Now A: [0,4,14,9,8,16,3,10,2,1,7]? Wait let's recalc: after i=2 swap: A[2]=14, A[4]=1. Then max_heapify(4) where i=4: l=8-> A[8]=2, r=9-> A[9]=8. Compare A[4]=1 with A[8]=2 => largest=8; then compare A[9]=8 >2 => largest=9. So swap A[4] and A[9]: A[4]=8, A[9]=1. So now A: index1:4,2:14,3:9,4:8,5:16,6:3,7:10,8:2,9:1,10:7. Then max_heapify(9) does nothing.
i=1: l=2,r=3; A[1]=4, A[2]=14 => largest=2; then compare r=3: A[3]=9 <14? Actually largest currently 2, so compare A[3] with A[2]=14, 9<14, so largest remains 2. Swap A[1]=14, A[2]=4. Call max_heapify(2): i=2; l=4, r=5; A[2]=4, A[4]=8 => largest=4; compare r=5: A[5]=16 >8 => largest=5. Swap A[2]=16, A[5]=4. Call max_heapify(5): i=5; l=10, r=11; A[5]=4, A[10]=7 => largest=10; swap A[5]=7, A[10]=4. Call max_heapify(10): i=10; l=20, r=21 out, stop. Now A: index1:14,2:16,3:9,4:8,5:7,6:3,7:10,8:2,9:1,10:4? Actually after max_heapify(5) swap we set A[5]=7, A[10]=4. So final A: [14,16,9,8,7,3,10,2,1,4]? That's not the expected. Let's compute step by step to ensure we get expected [16,14,10,8,7,9,3,2,4,1].
Maybe I messed up the order. Let's recalc carefully:
Initial: [0,4,1,3,2,16,9,10,14,8,7]
i=5: max_heapify(5): node5=16, left=10:7, right=11 (none). So nothing.
i=4: max_heapify(4): node4=2, left=8:14, right=9:8 -> largest=8 (14>2). swap A[4]=14, A[8]=2 -> array becomes [0,4,1,3,14,16,9,10,2,8,7]. Then call max_heapify(8): node8=2, left=16 (none), right=17 (none). No change.
i=3: max_heapify(3): node3=3, left=6:9, right=7:10 -> largest=7? Actually compare left:9>3 -> largest=6, then right:10>9 -> largest=7. So swap A[3]=10, A[7]=3 -> array becomes [0,4,1,10,14,16,9,3,2,8,7]. Then call max_heapify(7): node7=3, left=14 (none), right=15 (none). No change.
i=2: max_heapify(2): node2=1, left=4:14, right=5:16 -> largest=5? Compare left:14>1 -> largest=4; then right:16>14 -> largest=5. So swap A[2]=16, A[5]=1 -> array becomes [0,4,16,10,14,1,9,3,2,8,7]. Then call max_heapify(5): node5=1, left=10:7, right=11 none -> compare left:7>1 -> largest=10. swap A[5]=7, A[10]=1 -> array becomes [0,4,16,10,14,7,9,3,2,8,1]. Then call max_heapify(10): node10=1, left=20 none -> stop.
i=1: max_heapify(1): node1=4, left=2:16, right=3:10 -> largest=2 (16>4). So swap A[1]=16, A[2]=4 -> array becomes [0,16,4,10,14,7,9,3,2,8,1]. Then call max_heapify(2): node2=4, left=4:14, right=5:7 -> largest=4 (14>4). swap A[2]=14, A[4]=4 -> array becomes [0,16,14,10,4,7,9,3,2,8,1]. Then call max_heapify(4): node4=4, left=8:2, right=9:8 -> largest=9 (8>4). swap A[4]=8, A[9]=4 -> array becomes [0,16,14,10,8,7,9,3,2,4,1]. Then call max_heapify(9): node9=4, left=18 none -> stop.
Now final array: index1..10 = [16,14,10,8,7,9,3,2,4,1] yes. So algorithm works.
Now we need to implement.
But I notice: in my earlier step-by-step I got different because I swapped at i=2 incorrectly? In the recalc I used correct order. So final answer is correct.
Now output: with leading space? I'll use:
print(' ' + ' '.join(map(str, A[1:])))
But careful: join produces a string; if H=0, there is no element, then ' ' + '' yields a single space? But H>=1 probably.
Alternatively, to be safe with any judge that may not accept leading space, we can check typical AOJ problem. In AOJ ALDS1_9_B, the expected output is indeed with a leading space. I recall that problem statement: "Print a space before each key." So output starts with a space. For example, sample output: " 16 14 10 8 7 9 3 2 4 1". Many solutions print like:
print('', *A[1:]) # results in leading space
Or print(' ' + ' '.join(map(str, A[1:]))).
I'll use the join method.
Now final code: Use sys.stdin.read() to read all input.
We'll include recursion limit? Not needed.
Now I'll produce final answer.
But note: The problem says "Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code." So we need to implement exactly as described.
Now final code.
Also note: There's no need to output any other text.
Now I'll produce the solution in Python.
Let's write:
import sys
def max_heapify(A, i, H):
l = i * 2
r = i * 2 + 1
largest = i
if l <= H and A[l] > A[largest]:
largest = l
if r <= H and A[r] > A[largest]:
largest = r
if largest != i:
A[i], A[largest] = A[largest], A[i]
max_heapify(A, largest, H)
def build_max_heap(A, H):
for i in range(H // 2, 0, -1):
max_heapify(A, i, H)
def main():
data = sys.stdin.read().strip().split()
if not data:
return
H = int(data[0])
A = [0] + list(map(int, data[1:1+H]))
build_max_heap(A, H)
# Output with a space before each value
out = ' ' + ' '.join(map(str, A[1:]))
print(out)
if name == "main":
main()
I think that's fine.
We can also skip recursion by using iterative version. But recursion depth is shallow.
Now produce final answer. ```python
import sys
def max_heapify(A, i, H):
"""
Make the subtree rooted at i a max-heap,
assuming the subtrees of its children are already max-heaps.
"""
l = 2 * i # left child
r = 2 * i + 1 # right child
largest = i
if l <= H and A[l] > A[largest]:
largest = l
if r <= H and A[r] > A[largest]:
largest = r
if largest != i:
A[i], A[largest] = A[largest], A[i] # swap
max_heapify(A, largest, H) # continue downward
def build_max_heap(A, H):
"""Convert the array A[1..H] into a max-heap."""
for i in range(H // 2, 0, -1):
max_heapify(A, i, H)
def main():
data = sys.stdin.read().split()
if not data:
return
H = int(data[0])
# store elements with 1‑based indexing
A = [0] + list(map(int, data[1:1 + H]))
build_max_heap(A, H)
# print with a single space before each value (as required)
print(' ' + ' '.join(map(str, A[1:])))
if name == "main":
main()