Memory Allocation Simulator
Time limit1sMemory limit128 MB
Simulate first-fit memory allocation and freeing over 100,000 memory cells while processing malloc, free, and print commands on named variables.
- Level
Medium6 of 10
- Topics
- Simulation, Implementation, Sorting
- Solved
- No attempts yet
Problem
Write a program that executes memory allocation commands in order.
The memory consists of 100,000 consecutive cells, addressed from 1 to 100,000. Initially, every cell is free.
Each command is one of the following.
var=malloc(size);- Find the earliest starting address of a contiguous free block of length
size. If such a block exists, allocate it and store its starting address invar. If no such block exists, store0. (100 ≤size≤ 100,000) - If
varalready stores another address, that old allocation is not freed automatically.
- Find the earliest starting address of a contiguous free block of length
free(var);- If
varstores the starting address of a block from a previous successfulmalloc, free that block and store0invar. Ifvaris already0, nothing happens.
- If
print(var);- Output the value stored in
var.
- Output the value stored in
Every command ends with a semicolon (;). A variable name consists of exactly four lowercase English letters. There are at most 1,000 distinct variables, and every variable is initialized to 0.
Input
The first line contains the number of commands N. (1 ≤ N ≤ 100,000)
Each of the next N lines contains one command, in the order it is executed.
At least one print command is given.
Output
For each print command, output its result on its own line.