#C2998. Simulated Memory Heap Manager
Simulated Memory Heap Manager
Simulated Memory Heap Manager
You are tasked with simulating a simplified memory heap manager. The memory heap is represented as an array of n cells (numbered from 1 to n), each initially free.
You need to process m commands. Each command is one of the following:
- ALLOC x: Allocate a contiguous block of x free cells. If such a block exists, choose the block with the smallest starting index, mark it as allocated, and output the starting index of the allocation (1-indexed). If no such block exists, output \( -1 \).
- FREE i: Free the memory block that was allocated starting at index i. If the block exists (i.e. i is a valid starting index of an allocated block), free the block (mark the cells as free) and output \( 0 \). Otherwise, output \( -1 \).
Input and Output: Read input from stdin and write output to stdout. The input format is described below.
Note: Ensure your solution maintains the memory state across operations and that it passes all test cases.
inputFormat
The first line contains two integers \( n \) and \( m \) separated by a space, where \( n \) is the number of cells in the memory heap, and \( m \) is the number of commands.
The next \( m \) lines each contain one command. Each command is either of the form ALLOC x
or FREE i
.
outputFormat
For each command, output a single line containing the result of the operation:
- For
ALLOC
commands, output the starting index (1-indexed) of the allocated block, or \( -1 \) if allocation fails. - For
FREE
commands, output \( 0 \) if the block is successfully freed, or \( -1 \) if the specified index does not correspond to an allocated block.
10 6
ALLOC 5
ALLOC 4
FREE 1
ALLOC 6
ALLOC 1
FREE 5
1
6
0
-1
1
-1
</p>