An array that doubles
Build a growable array of integers yourself.
The array keeps the number of elements (its size) separately from the number of slots it has borrowed memory for (its capacity).
At the start the size is 0 and the capacity is 1.
There are four commands.
- push x: if the size equals the capacity, first double the capacity (one grow), then append x at the end.
- pop: if the array is empty, print empty.
Otherwise remove the last value and print it; after that, if the capacity is at least 2 and size×4 is at most the capacity, halve the capacity (one shrink).
- get i: print the value at index i, counting from 0.
If i is at least the size, print out of range.
- info: print the size and the capacity separated by one space.
The first line gives the number of commands q, and the next q lines give one command each.
Print the output above for each command, one line each, and on the last line print "grow number_of_grows shrink number_of_shrinks".
The capacity that info prints is always the value given by the rules above.
In C, resize the borrowed block with realloc; in C++, keep count of the capacity yourself in a variable and borrow that much ahead of time with std::vector's reserve.
- Input
- 1 ≤ q ≤ 100,000, -1,000,000,000 ≤ x ≤ 1,000,000,000, 0 ≤ i ≤ 100,000 (integers)
- Output
- one line for each command other than push, then "grow G shrink S"
9 push 4 push 8 push 15 info get 2 pop pop info get 1
3 4 15 15 8 1 2 out of range grow 2 shrink 1