Cutting, pasting and reversing video clips with prev and next pointers
n video clips, numbered 1 to n, are joined in a line in that order.
There are three commands.
- move a b c: of clip a and clip b, take the one that is currently earlier and the one that is currently later, cut out the run of clips from the earlier one to the later one, and paste it right after clip c.
If c is 0, paste it at the very front.
The order inside the run stays the same.
- However, if clip c is inside that run (clips a and b themselves included), move does nothing.
- rev a b: reverse the order of the run chosen in the same way.
- near x: print on one line the number of the clip right before clip x and the number of the clip right after it, separated by a single space.
If there is no clip before or after, print 0 in that place.
a and b may be equal; then the run is that one clip.
The first line gives n and the number of commands q, and the next q lines give one command each.
Print one line for each near, and on the last line print the n clip numbers from the front after all commands, separated by single spaces.
Try solving it with a doubly linked list where each clip holds its number and pointers prev and next to the clips before and after it.
If you add a head node numbered 0 and make the first clip's prev and the last clip's next point to it, you do not need to treat the two ends specially.
Create all nodes in one array at the start, and get the address of clip x's node directly as &nodes[x].
Reverse a run without copying numbers around: swap prev and next in every node of the run, then link the two ends of the run back to the nodes outside it.
Grading looks only at the output.
- Input
- 1 ≤ n ≤ 10,000, 1 ≤ q ≤ 5,000.
a and b ofmoveandrev, and x ofnear, are integers from 1 to n; c ofmoveis an integer from 0 to n. - Output
- One line per
near(the numbers of the clips before and after), and on the last line the n clip numbers from the front
6 6 move 5 2 0 rev 1 3 near 2 move 1 4 3 move 3 1 1 near 6
0 1 4 0 2 3 1 5 4 6
5 7 rev 2 4 near 3 near 2 rev 5 1 near 5 near 4 move 4 4 2
4 2 3 5 0 2 3 1 5 2 4 3 1