<|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.

324. The Text Formatting
Time limit per test: 0.25 second(s)
Memory limit: 65536 kilobytes
input: standard
output: standard



The Library of Berland has an ancient document with text composed of words, spaces and "-"  characters. A word is a sequence of Latin letters. The chief librarian asked you to format the text from the document by adding and removing spaces. There are special rules for using the "-"  character in the ancient documents which you need to obey.

The "-"  character can be used as:
Hyphen, in this case a word should be started and finished to the right and to the left from it. For example, "co-coach" .
A part of the short dash, in this case two characters "-"  should be used with a space to the right and to the left. For example, " -- " .
A part of the long dash, in this case three characters "-"  should be used with a space to the right and to the left. For example, " --- " .


If there is no "-"  character between words, the words should be delimited by a single space.

The resulting text should not have any other space characters.

Input
The first line of the input contains N (1 ≤ N ≤ 100) — the number of lines with the text of the document to be formatted. Each of the following N lines contains the quoted text of the document to be formatted. The length of the text of each document is not less than 1 and not more than 100 characters.

Output
For each document from the input write a separate line with the formatted text enclosed in quotes to the output. If it is impossible to correctly format the text, write the only word "error"  without quotes. If there are several solutions, choose any of them.

Example(s)
sample input
sample output
3
"This is sample -mample "
"No solution-"
"This is - - --possible test- -"
"This is sample-mample"
error
"This is -- -- possible test -- "

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

You are given **N (≤ 100)** quoted lines. Each line contains only **Latin letters**, **spaces**, and **'-'**.

You may **add/remove spaces** (but cannot change letters or hyphens) to produce a formatted text that follows:

- **Words** are maximal sequences of letters.
- If there is **no '-' between two adjacent words**, they must be separated by **exactly one space**.
- A single `-` is a **hyphen** and must be **between two words**: `word-word` (no spaces around).
- A **short dash** is exactly `--` with **one space on both sides**: `" -- "`.
- A **long dash** is exactly `---` with **one space on both sides**: `" --- "`.

The output must contain **no other spaces**.
For each line, output the formatted text in quotes, or `error` if impossible.

---

## 2) Key observations

1. **Spaces are irrelevant for parsing** because we're allowed to add/remove them.
   What matters is only:
   - the sequence of **words**,
   - the number of `-` characters occurring **before the first word**, **between words**, and **after the last word** (ignoring spaces).

2. A run of `k` hyphens can be interpreted as:
   - `k = 0`: normal word separator (single space between words)
   - `k = 1`: **hyphen**, valid **only between two words**
   - `k ≥ 2`: must be expressed using **short/long dashes** with spaces around.
     This is always possible:
     - even `k`: all short dashes (2 each)
     - odd `k`: one long dash (3) + remaining short dashes (2 each)

3. **Single hyphen at the boundaries is impossible**:
   - Before the first word: `k = 1` cannot be a hyphen (no left word)
   - After the last word: `k = 1` cannot be a hyphen (no right word)

4. If the line contains **no words**, it contains only spaces and `-`:
   - total hyphens = 1 ⇒ impossible (`error`)
   - total hyphens = 0 ⇒ result is empty `""`
   - total hyphens ≥ 2 ⇒ format as dashes only

---

## 3) Full solution approach

For each input line:

### Step A: Read and validate quotes
- Input line must start and end with `"`; take the inside as `text`.
- If not properly quoted, treat as `error`.

### Step B: Parse into words and dash counts
Scan `text` left to right:
- Ignore spaces.
- Count hyphens into `dash_count`.
- When you encounter a letter, you start a word:
  - push current `dash_count` into array `dashes` (it's "before this word"),
  - reset `dash_count = 0`,
  - read the whole word (letters only) and append to `words`.
- If any character is not space, `-`, or letter ⇒ `error`.
At the end, append the remaining `dash_count` as trailing dashes (after last word).

This gives:
- `words = [w0, w1, ..., w(n-1)]`
- `dashes = [d0, d1, ..., dn]`
  where `d0` before first word, `dn` after last word.

### Step C: Validate
- If `words` is empty:
  - if `dashes[0] == 1` ⇒ `error`
  - else output formatted dash-only string.
- Otherwise:
  - if `dashes[0] == 1` or `dashes[n] == 1` ⇒ `error` (hyphen cannot be at boundaries)

### Step D: Reconstruct formatted output
Define a function `dash_string(k)`:
- `k=0` → `""`
- `k=1` → `"-"` (only used between words)
- `k≥2` → build canonical representation:
  - if `k` odd: start with `" --- "`, subtract 3
  - else: start with `" -- "`, subtract 2
  - while remaining `k>0`, append `"-- "` and subtract 2
  (This matches the classic editorial approach and keeps spacing valid.)

Build output:
- leading `dash_string(d0)` if `d0>0`
- word0
- for each next word `wj`:
  - if `dj==0`: append `" "`
  - if `dj==1`: append `"-"`
  - if `dj>=2`: append `dash_string(dj)`
  - append `wj`
- trailing `dash_string(dn)` if `dn>0`
Wrap in quotes.

Complexity: **O(L)** per line, with L ≤ 100.

---

## 4) C++ implementation

```cpp
#include <bits/stdc++.h>

using namespace std;

template<typename T1, typename T2>
ostream& operator<<(ostream& out, const pair<T1, T2>& x) {
    return out << x.first << ' ' << x.second;
}

template<typename T1, typename T2>
istream& operator>>(istream& in, pair<T1, T2>& x) {
    return in >> x.first >> x.second;
}

template<typename T>
istream& operator>>(istream& in, vector<T>& a) {
    for(auto& x: a) {
        in >> x;
    }
    return in;
};

template<typename T>
ostream& operator<<(ostream& out, const vector<T>& a) {
    for(auto x: a) {
        out << x << ' ';
    }
    return out;
};

string text;

bool is_letter(char c) {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

void read() {
    string line;
    getline(cin, line);
    while(!line.empty() && (line.back() == '\r' || line.back() == '\n')) {
        line.pop_back();
    }
    if(line.size() >= 2 && line.front() == '"' && line.back() == '"') {
        text = line.substr(1, line.size() - 2);
    } else {
        text = "\x01";
    }
}

string dash_string(int k) {
    if(k == 0) {
        return "";
    }
    if(k == 1) {
        return "-";
    }

    string result;
    if(k % 2 == 1) {
        result = " --- ";
        k -= 3;
    } else {
        result = " -- ";
        k -= 2;
    }
    while(k > 0) {
        result += "-- ";
        k -= 2;
    }
    return result;
}

void solve() {
    // This is more of an exercise in parsing. There isn't really a complicated
    // algorithms idea here. We extract words and count dashes between them,
    // then validate that boundary dashes can be expressed as short/long dashes
    // (not single hyphens which require words on both sides).

    vector<string> words;
    vector<int> dashes;

    int dash_count = 0;
    int i = 0;
    while(i < (int)text.size()) {
        char c = text[i];
        if(c == ' ') {
            i++;
        } else if(c == '-') {
            dash_count++;
            i++;
        } else if(is_letter(c)) {
            dashes.push_back(dash_count);
            dash_count = 0;
            string word;
            while(i < (int)text.size() && is_letter(text[i])) {
                word += text[i];
                i++;
            }
            words.push_back(word);
        } else {
            cout << "error\n";
            return;
        }
    }
    dashes.push_back(dash_count);

    if(words.empty()) {
        if(dash_count == 1) {
            cout << "error\n";
        } else if(dash_count > 1) {
            cout << "\"" << dash_string(dash_count) << "\"\n";
        } else {
            cout << "\"\"\n";
        }
        return;
    }

    int n = words.size();
    if(dashes[0] == 1 || dashes[n] == 1) {
        cout << "error\n";
        return;
    }

    ostringstream oss;
    if(dashes[0] > 0) {
        oss << dash_string(dashes[0]);
    }
    oss << words[0];

    for(int j = 1; j < n; j++) {
        int k = dashes[j];
        if(k == 0) {
            oss << " ";
        } else if(k == 1) {
            oss << "-";
        } else {
            oss << dash_string(k);
        }
        oss << words[j];
    }

    if(dashes[n] > 0) {
        oss << dash_string(dashes[n]);
    }

    cout << "\"" << oss.str() << "\"\n";
}

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

    int T;
    cin >> T;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    for(int test = 1; test <= T; test++) {
        read();
        solve();
    }

    return 0;
}
```

---

## 5) Python implementation (detailed comments)

```python
import sys

def is_letter(c: str) -> bool:
    """True if c is an ASCII Latin letter."""
    return ('a' <= c <= 'z') or ('A' <= c <= 'Z')

def dash_string(k: int) -> str:
    """
    Convert k consecutive '-' into a valid representation:
    k=0 -> ""
    k=1 -> "-" (hyphen; only valid between words)
    k>=2 -> combination of short dash " -- " (2 hyphens) and possibly one long dash " --- " (3 hyphens).
    """
    if k == 0:
        return ""
    if k == 1:
        return "-"

    # Canonical build: start with a long dash if k is odd, else short dash.
    if k % 2 == 1:
        res = " --- "
        k -= 3
    else:
        res = " -- "
        k -= 2

    # Append remaining short dashes. Each adds 2 hyphens.
    while k > 0:
        res += "-- "
        k -= 2
    return res

def solve_one(line_raw: str) -> str:
    """Return 'error' or a quoted formatted string for one input line."""
    line_raw = line_raw.rstrip("\r\n")

    # Validate and strip quotes
    if len(line_raw) < 2 or line_raw[0] != '"' or line_raw[-1] != '"':
        return "error"
    text = line_raw[1:-1]

    words = []
    dashes = []

    dash_count = 0
    i = 0

    # Parse: ignore spaces, count hyphens, extract words
    while i < len(text):
        c = text[i]
        if c == ' ':
            i += 1
        elif c == '-':
            dash_count += 1
            i += 1
        elif is_letter(c):
            # record dashes before this word
            dashes.append(dash_count)
            dash_count = 0

            # read the full word
            j = i
            while j < len(text) and is_letter(text[j]):
                j += 1
            words.append(text[i:j])
            i = j
        else:
            return "error"

    # trailing dashes
    dashes.append(dash_count)

    # No words: only spaces and hyphens
    if not words:
        if dash_count == 1:
            return "error"
        if dash_count == 0:
            return '""'
        return '"' + dash_string(dash_count) + '"'

    n = len(words)

    # Boundary cannot have a single hyphen
    if dashes[0] == 1 or dashes[n] == 1:
        return "error"

    out = []

    # leading dashes
    if dashes[0] > 0:
        out.append(dash_string(dashes[0]))

    # first word
    out.append(words[0])

    # between words
    for j in range(1, n):
        k = dashes[j]
        if k == 0:
            out.append(" ")
        elif k == 1:
            out.append("-")
        else:
            out.append(dash_string(k))
        out.append(words[j])

    # trailing dashes
    if dashes[n] > 0:
        out.append(dash_string(dashes[n]))

    return '"' + "".join(out) + '"'

def main():
    data = sys.stdin.read().splitlines()
    if not data:
        return
    N = int(data[0].strip())
    ans = []
    for i in range(1, 1 + N):
        ans.append(solve_one(data[i] if i < len(data) else ""))
    sys.stdout.write("\n".join(ans))

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