The Conga Line

easy linked-list simulation 1000 ms · 256 MB

The Conga Line

At the party, n dancers numbered 1 to n form a conga line, standing in that order from front to back: dancer 1 leads, dancer 2 is right behind them, and so on down to dancer n at the very back.

Over the course of the night, m events happen to the line, each one of three kinds:

  • BEHIND x y — dancer x slips out of their current spot and cuts back in directly behind dancer y (dancer y does not move; x simply ends up immediately behind them).
  • FRONT x — dancer x slips out of their current spot and runs all the way to the front of the line, becoming the new leader.
  • LEAVE x — dancer x slips out of the line and goes home for the night. They take no further part in the party.

You may assume the party is well organized: every event names dancers who are still at the party (nobody who has already done LEAVE is ever named again, either as x or as y), and in a BEHIND x y event x and y are always two different dancers.

After all m events, print the dancers who are still in the line, from front to back.

Input

The first line contains two integers n and m (1 ≤ n ≤ 2·10^5, 0 ≤ m ≤ 2·10^5).

Each of the next m lines describes one event, in one of the forms above, where x and y are dancer numbers between 1 and n.

Output

Print the dancers still in the line after all events, from front to back, separated by single spaces, on one line. If nobody is left, print an empty line.

Notes

In the first example, dancer 1 cuts in behind dancer 3, turning 1 2 3 4 5 into 2 3 1 4 5. Then dancer 5 runs to the front, giving 5 2 3 1 4. Finally dancer 3 leaves, giving the final line 5 2 1 4.

Example 1

Input

5 3
BEHIND 1 3
FRONT 5
LEAVE 3

Output

5 2 1 4

Example 2

Input

4 4
FRONT 3
BEHIND 4 3
LEAVE 1
FRONT 2

Output

2 3 4

Hints · reveal one at a time if you're stuck

Hint 1

Moving a dancer by rebuilding an array means shifting many others on every event. Which structure lets you remove one dancer and re-insert them right after another in constant time?

Hint 2

Link each dancer to the neighbour in front and the neighbour behind, and add one placeholder node that stands for the position just ahead of the leader. Every event is then an unlink followed by an insertion after a known node, and you walk the links once at the end.

report an issue Prefer your own editor? sooks prep 69 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.