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

393. Bergamot Problem
Time limit per test: 1.25 second(s)
Memory limit: 65536 kilobytes
input: standard
output: standard



Berland alphabet consists of N letters, which are first N latin letters. Citizens of Berland use simple abbreviation scheme for SMS writing purposes. Each word is abbreviated to the sequence of two symbols — its first and last letters. For example, the word "" is abbreviated to "". Unfortunately, for single-letter words this rule leads to a word lengthening. For example, word "" will be written as "".

Vocabulary used for SMS creation consists of only two-character words. The numerous studies of well-known scientists showed that the vocabulary consists of M distinct words.

Bergamot company is ready to put their new cell phone in production. The new model is planned to have the revolutionary system of a quick text input (somewhat similar to the famous T9). Keyboard of the phone will consist of K buttons. Each button will have one or several letters from placed on it. Each letter can be placed on exactly one button of the phone. In order to enter a word, a user should press two buttons on the phone one after another: button with the first letter of the word, and then button with the last letter of the word. Placement of letters on the keyboard is called  for a given vocabulary, if there are no words from vocabulary that can be entered using the same two-buttons sequence.

For example, if the vocabulary consists of three words "", "" and "", two buttons are enough for creating the keyboard. The first button will have "" and "", the second button — "". The placement like "" and "" on the first button, "" on the second button will not work, because words "" and "" can be entered using the same sequence of buttons.

Bergamot engineers have got a problem finding optimal placement of Berland alphabet letters on the keyboard of the phone. The  placement is any correct placement with the minimal possible number of buttons used for the given Berland alphabet.

Input
The first line of the input contains two integer numbers N, M (1 ≤ N ≤ 13; 0 ≤ M ≤ 50). The following M lines contain words from the vocabulary — one word per line. Each word consists of exactly two lowercase Latin letters. Only first N letters from Latin alphabet can be used. All words in the vocabulary are different.

Output
The first line of the output file should contain the minimal possible number of the keyboard buttons K for the optimal letters placement. The placement itself should be printed to the following K lines. The i+1th line of the output file should contain letters placed on the ith button. The order of letters within each line, and the order of lines describing the placement don't matter. If there are several solutions, you may output any of them.

Example(s)
sample input
sample output
3 3
ab
aa
bc
2
ac
b

sample input
sample output
4 2
ab
cd
2
cb
ad

sample input
sample output
5 4
aa
bb
cc
dd
4
ae
b
c
d

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

You have an alphabet of size **N ≤ 13** (letters `a..`). There are **M ≤ 50** distinct **2-letter words** (ordered pairs) in a vocabulary.

You must partition the N letters into **K buttons** (each letter on exactly one button). A word `xy` is typed by pressing the button containing `x`, then the button containing `y`.

A placement is **correct** if **no two different words** are typed by the **same ordered pair of buttons**.  
Find the **minimum K** and output any valid partition.

---

## 2) Key observations

1. **Graph model**: Treat letters as vertices `0..N-1`. Each word `xy` is a **directed edge** `x → y`.

2. **Buttons = partition into groups**: If letters are partitioned into groups (buttons) `G1..GK`, then typing a word corresponds to an ordered pair of groups `(Gi, Gj)`.

3. **Correctness constraint**:
   For every ordered pair of groups `(A, B)`, there must be **at most one** vocabulary edge `u → v` with `u ∈ A` and `v ∈ B`.  
   This includes the case `A = B` (edges inside one button).

4. **N is small ⇒ bitmasks**: Since `N ≤ 13`, any subset of letters fits into an integer bitmask (0..2^N−1). We can precompute properties for all subsets.

5. **Monotonicity in K**: If a partition is possible with K buttons, it’s also possible with K+1 (split any group).  
   ⇒ We can **binary search** the minimum K and test feasibility.

6. **Avoid huge partition enumeration**: The number of set partitions is large (Bell numbers). Instead, do a **DFS** that:
   - always puts the **lowest remaining letter** into the next group (removes symmetry),
   - enumerates possible groups containing it,
   - prunes by fast compatibility checks.

---

## 3) Full solution approach

### Step A — Build adjacency bitmasks
Index letters `0..N-1`.

- `out[u]`: bitmask of all `v` such that edge `u → v` exists
- `in[v]`: bitmask of all `u` such that edge `u → v` exists

### Step B — Precompute subset information for all `mask`
For each subset `mask`:

1. `any_out[mask]` = union of all outgoing targets from vertices in `mask`  
   `any_out[mask] = OR(out[u])` for `u ∈ mask`

2. `dang_out[mask]` = set of vertices `v` that receive edges from **at least two different** vertices in `mask`  
   This helps detect collisions where two different edges would map to the same button-pair.

3. `int_cnt[mask]` = number of directed edges fully inside `mask`  
   Internal validity requires `int_cnt[mask] ≤ 1` because `(Gi,Gi)` must also have ≤ 1 edge.

All these can be computed by subset DP:
take `u = least significant set bit of mask`, `prev = mask without u`, and update.

### Step C — O(1) compatibility test between two groups
For disjoint groups `g` and `h`, need:
- edges from `g` to `h`: **≤ 1**
- edges from `h` to `g`: **≤ 1**

Using precomputed arrays:

`g → h` is invalid if:
- `dang_out[g]` intersects `h` (some vertex in `h` is hit by ≥2 sources from `g`)
- OR `popcount(any_out[g] & h) > 1` (g hits ≥2 distinct vertices in h)

Check both directions.

### Step D — Feasibility check for a fixed K (DFS)
Goal: partition all letters into **≤ K** groups.

DFS state:
- `remaining` bitmask of unassigned letters
- `used` number of groups already chosen
- list `groups[]` of chosen group masks

Recurrence:
1. If `remaining == 0` ⇒ success.
2. If `used == K` but still remaining ⇒ fail.
3. Let `lo` be the lowest set bit of `remaining`. Force `lo` into the next group.
4. Enumerate all subsets `sub` of `rest = remaining \ {lo}` and set `group = sub ∪ {lo}`.
5. Accept `group` only if:
   - `int_cnt[group] ≤ 1`
   - compatible with all previously chosen groups
6. Recurse on `remaining \ group`.

This generates each partition only once (no permutation duplicates).

### Step E — Binary search minimal K
Binary search `K ∈ [1..N]`:
- run feasibility DFS for mid
- if feasible, try smaller; else try larger
Store the found groups for the best K.

### Complexity
- Precompute over all subsets: `O(N * 2^N)` (≤ ~106k ops)
- DFS is pruned heavily; `N=13` is small enough.
- Works comfortably within limits.

---

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

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

/*
  Bergamot Problem (N <= 13):
  Partition letters into minimum number of buttons so that every vocabulary word
  (directed edge u->v) maps to a unique ordered pair of buttons.

  Approach:
  - Model as directed graph on N vertices.
  - Bitmask DP precomputations for all subsets:
      any_out[mask]  = union of out-neighbors
      dang_out[mask] = vertices reached by >= 2 sources from mask
      int_cnt[mask]  = number of edges fully inside mask
  - Two groups g,h are compatible iff:
      - g -> h has <= 1 edge
      - h -> g has <= 1 edge
    using O(1) bit operations.
  - Binary search minimum K, with DFS feasibility check generating groups.
*/

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

    int n, m;
    cin >> n >> m;

    vector<string> words(m);
    for (int i = 0; i < m; i++) cin >> words[i];

    // Build adjacency as bitmasks.
    vector<int> out(n, 0), in(n, 0);
    for (auto &w : words) {
        int u = w[0] - 'a';
        int v = w[1] - 'a';
        out[u] |= (1 << v);
        in[v]  |= (1 << u);
    }

    int ALL = (1 << n);
    vector<int> any_out(ALL, 0), dang_out(ALL, 0), int_cnt(ALL, 0);

    // Precompute subset properties via DP over masks.
    // For mask != 0: pick least significant bit u, prev = mask without u.
    for (int mask = 1; mask < ALL; mask++) {
        int u = __builtin_ctz(mask);          // index of lsb set bit
        int prev = mask ^ (1 << u);

        // union of outgoing neighbors
        any_out[mask] = any_out[prev] | out[u];

        // targets that have >=2 incoming edges from this subset:
        // if a target was already hit by prev and is also hit by u, it becomes dangerous
        dang_out[mask] = dang_out[prev] | (any_out[prev] & out[u]);

        // count internal edges:
        // edges u->v with v in prev
        int add1 = __builtin_popcount(out[u] & prev);
        // edges v->u with v in prev (i.e., incoming to u from prev)
        int add2 = __builtin_popcount(in[u] & prev);
        // self-loop u->u if exists
        int loop = (out[u] >> u) & 1;

        int_cnt[mask] = int_cnt[prev] + add1 + add2 + loop;
    }

    auto compatible = [&](int g, int h) -> bool {
        // g -> h must have <= 1 edge
        if (dang_out[g] & h) return false; // some vertex in h is hit by >=2 sources in g
        if (__builtin_popcount(any_out[g] & h) > 1) return false; // hits >=2 targets in h

        // h -> g must have <= 1 edge
        if (dang_out[h] & g) return false;
        if (__builtin_popcount(any_out[h] & g) > 1) return false;

        return true;
    };

    // Storage for best solution found.
    int best_k = n;
    vector<int> best_groups(n);
    for (int i = 0; i < n; i++) best_groups[i] = (1 << i);

    vector<int> groups(n); // current groups being built

    // Feasibility DFS for fixed limit k.
    auto feasible = [&](int k) -> bool {
        bool found = false;

        function<void(int,int)> dfs = [&](int remaining, int used) {
            if (found) return;

            if (remaining == 0) {
                // Success: store solution
                found = true;
                best_k = used;
                for (int i = 0; i < used; i++) best_groups[i] = groups[i];
                return;
            }
            if (used >= k) return;

            // Force lowest remaining letter into next group to avoid symmetric duplicates.
            int lo = remaining & -remaining;
            int rest = remaining ^ lo;

            // Enumerate all submasks of rest; group = sub | lo
            for (int sub = rest;; sub = (sub - 1) & rest) {
                int g = sub | lo;

                // Internal constraint: at most one edge inside the group
                if (int_cnt[g] <= 1) {
                    bool ok = true;
                    for (int i = 0; i < used; i++) {
                        if (!compatible(g, groups[i])) { ok = false; break; }
                    }
                    if (ok) {
                        groups[used] = g;
                        dfs(remaining ^ g, used + 1);
                        if (found) return;
                    }
                }

                if (sub == 0) break;
            }
        };

        dfs((1 << n) - 1, 0);
        return found;
    };

    // Binary search the minimum k.
    int L = 1, R = n;
    while (L <= R) {
        int mid = (L + R) / 2;
        if (feasible(mid)) R = mid - 1;
        else L = mid + 1;
    }

    // Output best partition.
    cout << best_k << "\n";
    for (int i = 0; i < best_k; i++) {
        int mask = best_groups[i];
        for (int j = 0; j < n; j++) {
            if (mask & (1 << j)) cout << char('a' + j);
        }
        cout << "\n";
    }

    return 0;
}
```

---

## 5) Python implementation (detailed comments)

```python
import sys

def solve() -> None:
    data = sys.stdin.read().strip().split()
    if not data:
        return
    it = iter(data)
    n = int(next(it))
    m = int(next(it))
    words = [next(it) for _ in range(m)]

    # Directed graph as bitmasks
    out = [0] * n
    inn = [0] * n
    for w in words:
        u = ord(w[0]) - 97
        v = ord(w[1]) - 97
        out[u] |= 1 << v
        inn[v] |= 1 << u

    ALL = 1 << n
    any_out = [0] * ALL     # union of outgoing neighbors from subset
    dang_out = [0] * ALL    # vertices reached by >=2 sources from subset
    int_cnt = [0] * ALL     # count of edges fully inside subset

    # Subset DP precomputation
    for mask in range(1, ALL):
        lsb = mask & -mask
        u = lsb.bit_length() - 1
        prev = mask ^ lsb

        any_out[mask] = any_out[prev] | out[u]
        dang_out[mask] = dang_out[prev] | (any_out[prev] & out[u])

        add1 = (out[u] & prev).bit_count()   # edges u -> v, v in prev
        add2 = (inn[u] & prev).bit_count()   # edges v -> u, v in prev
        loop = (out[u] >> u) & 1             # u -> u
        int_cnt[mask] = int_cnt[prev] + add1 + add2 + loop

    def compatible(g: int, h: int) -> bool:
        # g -> h at most one edge
        if dang_out[g] & h:
            return False
        if (any_out[g] & h).bit_count() > 1:
            return False
        # h -> g at most one edge
        if dang_out[h] & g:
            return False
        if (any_out[h] & g).bit_count() > 1:
            return False
        return True

    best_k = n
    best_groups = [(1 << i) for i in range(n)]
    groups = [0] * n

    sys.setrecursionlimit(1_000_000)

    def feasible(k: int) -> bool:
        nonlocal best_k, best_groups
        found = False

        def dfs(remaining: int, used: int) -> None:
            nonlocal found, best_k, best_groups
            if found:
                return
            if remaining == 0:
                found = True
                best_k = used
                best_groups[:used] = groups[:used]
                return
            if used >= k:
                return

            lo = remaining & -remaining
            rest = remaining ^ lo

            sub = rest
            while True:
                g = sub | lo

                # Internal constraint for one group (Gi,Gi): <= 1 edge inside
                if int_cnt[g] <= 1:
                    ok = True
                    for i in range(used):
                        if not compatible(g, groups[i]):
                            ok = False
                            break
                    if ok:
                        groups[used] = g
                        dfs(remaining ^ g, used + 1)
                        if found:
                            return

                if sub == 0:
                    break
                sub = (sub - 1) & rest  # next submask

        dfs((1 << n) - 1, 0)
        return found

    # Binary search for minimum K
    L, R = 1, n
    while L <= R:
        mid = (L + R) // 2
        if feasible(mid):
            R = mid - 1
        else:
            L = mid + 1

    # Output
    out_lines = [str(best_k)]
    for i in range(best_k):
        mask = best_groups[i]
        s = []
        for j in range(n):
            if (mask >> j) & 1:
                s.append(chr(97 + j))
        out_lines.append("".join(s))
    sys.stdout.write("\n".join(out_lines))

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

This matches the intended editorial strategy: directed-graph reformulation, bitmask precomputation for constant-time checks, DFS with symmetry breaking, and binary search on the minimum number of buttons.