## Editorial for DMOPC '21 Contest 7 P2 - Knitting Scarves

Remember to use this editorial

**only**when stuck, and**not to copy-paste code from it**. Please be respectful to the problem author and editorialist.**Submitting an official solution before solving the problem yourself is a bannable offence.**Author:

## Hint

Doubly Linked List.## Full Solution

We will perform these queries on a Doubly Linked List to achieve a constant time.Each node in this Linked List will represent a node with a certain value. Each node will have a pointer to the next node and a pointer to the previous node. Thus, initially the node that holds value will point to for the next pointer and for the previous pointer. Note that to make the implementation easier, we can have nodes with value and to represent the head and tail of the Linked List.

When performing a query, it helps to see for every relevant part of the Linked List how will their pointers change. For a particular query we also need to keep track of

1. , which is the next pointer of

2. , which is the previous pointer of

3. , which is the next pointer of

The query makes

1. right after

2. right after

3. right after

When setting right after the next pointer of points to and the previous pointer of points to . It helps to draw the before and after visually. Finally, after performing all the operations, starting from the head of the Linked List, we can iterate through the nodes by using the next pointer until we reach the end.

Be careful when implementing. In particular, first take out the array that starts with value and ends with value first and then insert them back into their new appropriate spots.

## Comments