I am trying to solve this problem :
https://www.spoj.pl/problems/CERC07S/
I have identified that i need a datastructure in which reversing operations have lesser time complexity. I tried to create one using a doubly linked list, in which (i thought) reversing can be done in O(1) by just changing a value associated with the starting and ending node which indicates the direction of traversing the list. I tried to implement it but got stuck. Maybe the approach is wrong!
Are trees applicable here? If yes, how? Any ideas or links are appreciated?
Thanks in advance.
I agree with the doubly linked lists. Here’s one way to implement it.
For each node, have the two pointers as an array. Also in the node have the value of the number and a boolean variable dir. Initially, point the first pointer in each node to the previous node, point the second pointer to the next node, and set dir for all nodes to 0. As you traverse the linked list, keep track of a variable that has the direction, D. Set it to 1 at first. It indicates which pointer to follow to get to the next element at each node. When you arrive at a node, if dir is set to 1, set D to the NOT of D and continue to use D to find the next node.
To reverse a sequence of nodes, set dir to the NOT of dir in the last node and the node after the last node of the sequence of nodes that you want to reverse, point the correct pointer of the node before the sequence to the last element of the sequence (and vice versa), and point the correct pointer of the node after to the sequence to the first element of the sequence (and vice versa).
Hopefully, that gives you some idea of at least one way to go forward.