<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

166. Editor
time limit per test: 0.25 sec.
memory limit per test: 4096 KB
input: standard
output: standard



You are to write a simple text editor. This editor must supply next commands:

english lowercase letters or spaces: insert this letter in the current position of the cursor.
L: move cursor one position left. If current position in the beginning of the line, cursor mustn't move.
R: move cursor one position right. If the current position if after the end of the line, cursor must go beyond this end. If an english lowercase letter or space follows in command line, additional spaces must be added to the text.
U: move cursor a line up. If the current line is the first, cursor mustn't move.
D: move cursor a line down. If the current line is last, cursor mustn't move.
N: a new line must be added after the current. The part of the current line, which goes after the cursor position, must go on the new line. The cursor must go on the first position of the new line.
E: a cursor must move to a position after the end of the curent line.
H: a cursor must move to the first position of the current line.
X: current symbol must be deleted. The remaining part of the line must shift left. If the current position is after the end of the current line, additional spaces must be added to the current line and the next line must be attached to the current line; if the current position is after the end of the last line, nothing must happen.
B: the symbol before the the cursor must be deleted and the remaining part of the line must shift left. If the current position if after the end of the line, cursor must shift left one position. If the current symbol is the first of the line, then current line must be attached to the previous and remaining part must shift up; if the current symbol is the first symbol of the first line, nothing must happen.
Q: the editor must finish the work.


The editor starts from the blank file.

It is guaranted that in any moment while working length of each string does not exceed 1000 chars, and total number of commands does not exceed 20480.

Input
On the input there is the only line --- the list of commands of the editor.

Output
Write to the output the result of working of the editor. The EOLn (symbols with ASCII numbers 13 and 10) chars must be only between lines generated by editor (NOT after the last string!)

Sample test(s)

Input
lineRoUNLLLLline dDDDNline tline cLLLLLLNEUULLXRRRBXHBBHBBBBQsome left output

Output
line lined line t
line c
Author:	NNSU #2 team
Resource:	
Date:

<|response|>
## 1) Abridged problem statement (concise)

Simulate a simple text editor starting from an empty file (one empty line) with a cursor at `(line=0, column=0)`.  
Input is one line containing commands (up to 20480 characters). Commands:

- `a`–`z` or space: insert this character at the cursor position; cursor moves right.
- `L`, `R`: move cursor left/right by 1 (left can’t go below 0; right may go beyond end-of-line).
- `U`, `D`: move cursor up/down one line (if possible).
- `N`: split current line at cursor; the right part becomes a new line below; cursor goes to start of new line.
- `H`, `E`: move cursor to start/end of current line.
- `X`: delete character at cursor; if cursor is past end-of-line, pad spaces up to cursor and then merge next line into current (if next exists).
- `B`: backspace (delete before cursor); if at start of line, merge with previous line.
- `Q`: stop processing immediately.

Output the resulting text: lines separated by newline (`\n`) **without** an extra newline after the last line.

Constraints: each line length never exceeds 1000 during simulation.

---

## 2) Key observations

1. **Cursor column may be beyond end-of-line.**  
   This “virtual space” matters for `R`, and affects `X` and insertion.

2. **You only need to pad with spaces in specific situations:**
   - When inserting at `col > len(line)`, spaces must appear between end-of-line and the insertion point.
   - When executing `X` with `col >= len(line)` and there is a next line: pad current line up to `col` before merging the next line.

3. **Line split (`N`) should not create spaces.**  
   If the cursor is beyond end-of-line, splitting should behave as if cursor is at end-of-line (tail is empty). So clamp `col = min(col, len)` before splitting.

4. Because each line length is bounded by 1000, using `std::string` insert/erase (which are O(length)) is fine.

---

## 3) Full solution approach

Maintain:
- `vector<string> lines` — the document as a list of lines.
- `int row, col` — cursor position.
  - `row` is always a valid line index.
  - `col` can be any `>= 0` (can exceed `lines[row].size()`).

Initialize:
- `lines = {""}`, `row = 0`, `col = 0`.

Helper: `pad_line(row, col)`  
If `col > lines[row].size()`, extend the line to length `col` filled with spaces.

Process commands from left to right until `Q`:
- **Insert letter/space**: `pad_line`, insert at `col`, `col++`.
- **L**: `col = max(0, col-1)`.
- **R**: `col++`.
- **U/D**: move `row` within `[0, lines.size()-1]` (do not clamp `col`).
- **H/E**: `col = 0` or `col = len(line)`.
- **N (split)**:
  - clamp: `col = min(col, len(line))`
  - `tail = line.substr(col)`, `line = line.substr(0,col)`
  - insert `tail` as new line after `row`
  - `row++`, `col = 0`
- **X (delete at cursor)**:
  - if `col < len`: erase that character
  - else if next line exists: `pad_line(row,col)`, append `lines[row+1]`, remove `lines[row+1]`
  - else do nothing
- **B (backspace)**:
  - if `col > 0`:
    - if `col <= len`: erase character at `col-1`
    - `col--` (even if cursor was in virtual space)
  - else (col == 0):
    - if `row > 0`: merge line into previous; cursor goes to join point
    - else do nothing

Finally print all lines separated by `\n`, without trailing newline.

---

## 4) C++ implementation (detailed comments)

```cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    // Input is a single line of commands and may contain spaces => getline
    string commands;
    getline(cin, commands);

    // Document: start with one empty line
    vector<string> lines(1, "");
    int row = 0, col = 0; // cursor position; col may exceed lines[row].size()

    // Pad a line with spaces so that its length becomes at least c.
    auto pad_line = [&](int r, int c) {
        if (c > (int)lines[r].size()) {
            lines[r].resize(c, ' ');
        }
    };

    for (char cmd : commands) {
        if (cmd == 'Q') break;

        // Insert lowercase letter or space
        if ((cmd >= 'a' && cmd <= 'z') || cmd == ' ') {
            pad_line(row, col); // ensure insertion index exists
            lines[row].insert(lines[row].begin() + col, cmd);
            col++;
            continue;
        }

        if (cmd == 'L') {
            if (col > 0) col--;
        } else if (cmd == 'R') {
            col++; // may go beyond end-of-line
        } else if (cmd == 'U') {
            if (row > 0) row--;
        } else if (cmd == 'D') {
            if (row + 1 < (int)lines.size()) row++;
        } else if (cmd == 'H') {
            col = 0;
        } else if (cmd == 'E') {
            col = (int)lines[row].size();
        } else if (cmd == 'N') {
            // Split line at cursor. If cursor is beyond EOL, clamp to EOL.
            col = min(col, (int)lines[row].size());

            string tail = lines[row].substr(col);
            lines[row].erase(col); // keep prefix [0..col)

            lines.insert(lines.begin() + row + 1, tail);
            row++;
            col = 0;
        } else if (cmd == 'X') {
            // Delete at cursor, or merge with next line if cursor is at/after EOL.
            if (col < (int)lines[row].size()) {
                lines[row].erase(lines[row].begin() + col);
            } else if (row + 1 < (int)lines.size()) {
                // Need to pad spaces up to cursor before attaching next line.
                pad_line(row, col);
                lines[row] += lines[row + 1];
                lines.erase(lines.begin() + row + 1);
            }
            // If beyond end of last line => do nothing.
        } else if (cmd == 'B') {
            // Backspace: delete before cursor, or merge lines if at column 0.
            if (col > 0) {
                // If cursor is within actual text, delete character at col-1.
                if (col <= (int)lines[row].size()) {
                    lines[row].erase(lines[row].begin() + (col - 1));
                }
                // Even in virtual space, spec says cursor shifts left.
                col--;
            } else {
                // col == 0: if possible, merge with previous line
                if (row > 0) {
                    int join_pos = (int)lines[row - 1].size();
                    lines[row - 1] += lines[row];
                    lines.erase(lines.begin() + row);
                    row--;
                    col = join_pos;
                }
                // else: at start of first line => nothing
            }
        }
    }

    // Output: newline between lines, but not after the last line
    for (int i = 0; i < (int)lines.size(); i++) {
        if (i) cout << '\n';
        cout << lines[i];
    }
    return 0;
}
```

---

## 5) Python implementation (detailed comments)

```python
import sys

def solve() -> None:
    # Read the command line (may contain spaces). Remove trailing newline.
    commands = sys.stdin.readline()
    if commands.endswith("\n"):
        commands = commands[:-1]

    lines = [""]      # start with one empty line
    row, col = 0, 0   # cursor; col may be > len(lines[row])

    def pad_line(r: int, c: int) -> None:
        """Pad lines[r] with spaces until its length is at least c."""
        s = lines[r]
        if c > len(s):
            lines[r] = s + (" " * (c - len(s)))

    for cmd in commands:
        if cmd == "Q":
            break

        # Insert lowercase letter or space
        if ("a" <= cmd <= "z") or cmd == " ":
            pad_line(row, col)
            s = lines[row]
            lines[row] = s[:col] + cmd + s[col:]
            col += 1
            continue

        if cmd == "L":
            if col > 0:
                col -= 1

        elif cmd == "R":
            col += 1

        elif cmd == "U":
            if row > 0:
                row -= 1

        elif cmd == "D":
            if row + 1 < len(lines):
                row += 1

        elif cmd == "H":
            col = 0

        elif cmd == "E":
            col = len(lines[row])

        elif cmd == "N":
            # Split line at cursor; clamp cursor to end-of-line (no padding here).
            if col > len(lines[row]):
                col = len(lines[row])
            s = lines[row]
            head, tail = s[:col], s[col:]
            lines[row] = head
            lines.insert(row + 1, tail)
            row += 1
            col = 0

        elif cmd == "X":
            s = lines[row]
            if col < len(s):
                # delete character at cursor
                lines[row] = s[:col] + s[col+1:]
            elif row + 1 < len(lines):
                # pad up to cursor, then merge next line
                pad_line(row, col)
                lines[row] = lines[row] + lines[row + 1]
                del lines[row + 1]
            # else: beyond last line => do nothing

        elif cmd == "B":
            if col > 0:
                s = lines[row]
                # delete char before cursor only if it exists in real text
                if col <= len(s):
                    lines[row] = s[:col-1] + s[col:]
                col -= 1
            else:
                # col == 0: merge with previous line if possible
                if row > 0:
                    join_pos = len(lines[row - 1])
                    lines[row - 1] += lines[row]
                    del lines[row]
                    row -= 1
                    col = join_pos
                # else: at (0,0) do nothing

    sys.stdout.write("\n".join(lines))

if __name__ == "__main__":
    solve()
```

These implementations follow the command semantics precisely, including the tricky “cursor beyond end-of-line” behavior and the special padding rules.