Dynamic memory allocation
Time limit1sMemory limit1024 MB
Simulate a memory allocator over n bytes: allocate the leftmost run of l free bytes, or free a range and count how many bytes were actually freed.
- Level
Hard8 of 10
- Topics
- Intervals, Segment tree, Binary search
- Solved
- No attempts yet
Problem
Kamila is designing a new programming language. She has already written a precise specification for the memory management constructs, but the implementation is still missing. Build the memory management system her specification describes.
The available memory is an array of bytes numbered through . At the beginning every byte is free, meaning no byte is allocated. The system then processes a sequence of queries in order, allocating and freeing bytes.
An allocation query is given by one integer . The system finds a block of consecutive free bytes, allocates them, and returns the position of the first byte of that block. If several such blocks exist, the one starting at the smallest position is chosen. If no such block exists, the query is rejected and the system returns . A rejected query leaves the memory unchanged.
A freeing query is given by two integers and . The system marks the consecutive bytes starting at position as free and returns the number of bytes it actually freed. A byte counts as actually freed when it was not free immediately before the query.
Input
The first line contains the number of bytes in the memory and the number of queries ().
Each of the next lines describes one query. The first integer on a line is the query type, where means allocation and means freeing. An allocation query continues with one integer (). A freeing query continues with two integers and (, ).
Output
For every query, print the value returned by the system on its own line, in the given order.