Cow Line

Interview

Time limit1sMemory limit128 MB

Summary
Maintain a deque of cows under left/right insertions and left/right bulk removals, then print the remaining cows left to right.
Level

Medium4 of 10

Topics
Queue, Linked list, Implementation, Simulation
Solved
No attempts yet

Problem

Farmer John's cows are forming a single line. The line starts empty, and as time passes the cows join it one at a time, at either the left end or the right end. Every so often, KK cows at the left end or the right end all leave the line at once to go graze.

The cows join in numerical order (1,2,3,…1, 2, 3, \dots): each time a cow arrives, it is assigned the smallest number not yet used. Once a cow leaves the line, it never returns.

You are given SS operations (1≤S≤100,0001 \le S \le 100{,}000). Each operation is one of the following two kinds:

  • A cow joins the left end or the right end of the line.
  • KK cows leave from the left end or the right end of the line.

The input never asks for an operation that cannot be performed (for example, removing more cows than are currently in the line).

After processing all operations, print the numbers of the cows remaining in the line from left to right. The final line is guaranteed to be non-empty.

Input

  • Line 1: an integer SS.
  • Lines 2 to S+1S+1: each line contains one operation in one of four formats:
    • A L — a cow joins the left end of the line.
    • A R — a cow joins the right end of the line.
    • D L K — KK cows leave from the left end.
    • D R K — KK cows leave from the right end.

Output

Print the numbers of the cows remaining in the line from left to right, one number per line.

Hint

The table below traces how each operation changes the line for a sample sequence of ten operations.

OperationLine after operation (left → right)
A L1
A L2 1
A R2 1 3
A L4 2 1 3
D R 24 2
A R4 2 5
A R4 2 5 6
D L 12 5 6
A L7 2 5 6
A R7 2 5 6 8

Examples7

  1. Example 1

    Input
    10
    A L
    A L
    A R
    A L
    D R 2
    A R
    A R
    D L 1
    A L
    A R
    
    Expected output
    7
    2
    5
    6
    8
    
  2. Example 2

    Input
    1
    A L
    
    Expected output
    1
    
  3. Example 3

    Input
    1
    A R
    
    Expected output
    1
    
  4. Example 4

    Input
    3
    A L
    A L
    A L
    
    Expected output
    3
    2
    1
    
  5. Example 5

    Input
    3
    A R
    A R
    A R
    
    Expected output
    1
    2
    3
    
  6. Example 6

    Input
    5
    A R
    A R
    A R
    A R
    D L 2
    
    Expected output
    3
    4
    
  7. Example 7

    Input
    5
    A R
    A R
    A R
    A R
    D R 3
    
    Expected output
    1