## 1. Abridged Problem Statement

Given a Kakuro grid of size `n × m` (`2 ≤ n, m ≤ 6`), fill every white cell with a digit from `1` to `9`.

Each white cell belongs to exactly one horizontal run and one vertical run. For every run:

- digits must be distinct;
- their sum must equal the clue written in the adjacent black cell.

Black cells are described as:

- `.....` — white cell;
- `XXXXX` — black cell with no clues;
- `AA\BB` — black cell with vertical clue `AA` and/or horizontal clue `BB`, where `XX` means no clue.

Output any valid completed grid, printing `_` for black cells and the chosen digit for white cells.

The puzzle is guaranteed to have at least one solution.

---

## 2. Detailed Editorial

### Key Observations

The grid is very small: `n, m ≤ 6`, so there are at most `36` cells. However, brute-forcing `9^white_cells` is still too large.

Kakuro constraints are naturally grouped by **runs**:

- A horizontal run is a maximal sequence of adjacent white cells in one row.
- A vertical run is a maximal sequence of adjacent white cells in one column.
- Each white cell belongs to exactly two runs: one horizontal and one vertical.

For each run, we know:

- its clue sum;
- its length;
- the set of white cells inside it.

The important rule is:

> A run of length `k` and clue sum `S` must contain a subset of `k` distinct digits from `1..9` whose sum is `S`.

Therefore, instead of reasoning digit-by-digit only, we can precompute all valid digit sets for each possible `(length, sum)` pair.

---

### Step 1: Parse the Grid and Identify Runs

For each black clue cell `AA\BB`:

- if `BB != XX`, it defines a horizontal run to the right;
- if `AA != XX`, it defines a vertical run downward.

For every white cell in that run, store the corresponding run ID.

We maintain:

```
h_run[i][j] = horizontal run id of cell (i, j)
v_run[i][j] = vertical run id of cell (i, j)
```

Also store each run's clue sum and length.

---

### Step 2: Precompute Valid Digit Masks

Represent a set of digits using a bitmask over bits `1..9` (bit 0 unused).

For every mask:

- count how many digits it contains;
- compute its digit sum.

Then store it as valid for `(count, sum)`.

For every actual run, retrieve the list of valid masks matching its length and clue.

---

### Step 3: Backtracking with Strong Pruning

During search, maintain `h_used[run]` and `v_used[run]`: bitmasks of digits already placed in each run.

For a run, a digit is currently allowed if it appears in at least one valid full mask that is a superset of the current used mask. The allowed set (excluding already-used digits) is:

```
allowed = union_of(valid_masks_that_contain_used) minus used
```

For a white cell, candidates are:

```
candidates = allowed_by_horizontal_run & allowed_by_vertical_run
```

This is very powerful pruning.

---

### Step 4: Use MRV Heuristic

At every recursive step, choose the unfilled white cell with the fewest candidates (**Minimum Remaining Values** heuristic). It quickly detects contradictions and avoids wasting time on flexible cells.

---

### Complexity

At most `36` cells; `2^10 = 1024` masks to precompute (constant). The backtracking search space is exponential in the number of white cells in theory, but Kakuro subset pruning and MRV make it fast enough for `6 × 6`.

---

## 3. C++ Solution

```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;
};

int n, m;
vector<vector<string>> g;

void read() {
    cin >> n >> m;
    g.assign(n, vector<string>(m));
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            cin >> g[i][j];
        }
    }
}

void solve() {
    // The grid is tiny (n, m <= 6), so this is brute-force backtracking over
    // white cells with sudoku-style pruning. For every black cell that carries
    // a clue we precompute the horizontal and vertical "runs" it controls: the
    // clue value, the length of the run, and a per-run id so each white cell
    // knows which two runs it participates in.
    //
    // The strong pruning step is to enumerate, for every run, the full list of
    // valid digit subsets ahead of time: every subset of {1..9} of size equal
    // to the run length whose digits sum to the clue. There are very few of
    // these per run, and they encode all the real constraints of the puzzle.
    //
    // During search we keep, for every run, a bitmask of digits already placed
    // in it. The set of digits still allowed in run r is then the union of all
    // valid subsets that are supersets of the current used mask, minus that
    // mask itself. For a white cell the candidate digits are the intersection
    // of its two runs' allowed sets, which is a much tighter filter than any
    // min/max-sum bound.
    //
    // On top of that we use MRV: at each step we pick the unfilled white cell
    // with the smallest candidate set, which is the standard sudoku
    // "most-constrained variable" heuristic and collapses the search tree on
    // the harder tests.

    vector<vector<int>> h_run(n, vector<int>(m, -1));
    vector<vector<int>> v_run(n, vector<int>(m, -1));
    vector<int> h_clue, v_clue;
    vector<int> h_count, v_count;

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            const string& s = g[i][j];
            if(s[0] == '.' || s == "XXXXX") {
                continue;
            }

            string aa = s.substr(0, 2);
            string bb = s.substr(3, 2);

            if(bb != "XX") {
                int rid = (int)h_clue.size();
                h_clue.push_back(stoi(bb));
                int cnt = 0;
                for(int k = j + 1; k < m && g[i][k][0] == '.'; k++) {
                    h_run[i][k] = rid;
                    cnt++;
                }
                h_count.push_back(cnt);
            }

            if(aa != "XX") {
                int rid = (int)v_clue.size();
                v_clue.push_back(stoi(aa));
                int cnt = 0;
                for(int k = i + 1; k < n && g[k][j][0] == '.'; k++) {
                    v_run[k][j] = rid;
                    cnt++;
                }
                v_count.push_back(cnt);
            }
        }
    }

    vector<vector<vector<int>>> kak(10, vector<vector<int>>(46));
    for(int mask = 0; mask < (1 << 10); mask++) {
        if(mask & 1) {
            continue;
        }
        int cnt = __builtin_popcount(mask);
        int sum = 0;
        for(int x = 1; x <= 9; x++) {
            if(mask & (1 << x)) {
                sum += x;
            }
        }
        if(cnt <= 9 && sum <= 45) {
            kak[cnt][sum].push_back(mask);
        }
    }

    int H = (int)h_clue.size();
    int V = (int)v_clue.size();
    vector<vector<int>> h_subs(H), v_subs(V);
    for(int r = 0; r < H; r++) {
        h_subs[r] = kak[h_count[r]][h_clue[r]];
    }
    for(int r = 0; r < V; r++) {
        v_subs[r] = kak[v_count[r]][v_clue[r]];
    }

    vector<pair<int, int>> cells;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            if(g[i][j][0] == '.') {
                cells.push_back({i, j});
            }
        }
    }

    int total = (int)cells.size();
    vector<int> h_used(H, 0), v_used(V, 0);
    vector<bool> filled(total, false);
    vector<vector<int>> ans(n, vector<int>(m, 0));

    auto allowed_for = [](const vector<int>& subs, int used) {
        int allowed = 0;
        for(int t: subs) {
            if((t & used) == used) {
                allowed |= t;
            }
        }
        return allowed & ~used;
    };

    function<bool(int)> bt = [&](int placed) -> bool {
        if(placed == total) {
            return true;
        }

        vector<int> h_allowed(H), v_allowed(V);
        for(int r = 0; r < H; r++) {
            h_allowed[r] = allowed_for(h_subs[r], h_used[r]);
        }
        for(int r = 0; r < V; r++) {
            v_allowed[r] = allowed_for(v_subs[r], v_used[r]);
        }

        int best = -1, best_mask = 0, best_cnt = 100;
        for(int idx = 0; idx < total; idx++) {
            if(filled[idx]) {
                continue;
            }
            auto [i, j] = cells[idx];
            int cand = h_allowed[h_run[i][j]] & v_allowed[v_run[i][j]];
            int cnt = __builtin_popcount(cand);
            if(cnt < best_cnt) {
                best_cnt = cnt;
                best = idx;
                best_mask = cand;
                if(cnt <= 1) {
                    break;
                }
            }
        }

        if(best_cnt == 0) {
            return false;
        }

        auto [i, j] = cells[best];
        int hr = h_run[i][j], vr = v_run[i][j];
        filled[best] = true;

        for(int mask = best_mask; mask; mask &= mask - 1) {
            int bit = mask & -mask;
            int d = __builtin_ctz(bit);
            h_used[hr] |= bit;
            v_used[vr] |= bit;
            ans[i][j] = d;

            if(bt(placed + 1)) {
                return true;
            }

            h_used[hr] ^= bit;
            v_used[vr] ^= bit;
        }

        filled[best] = false;
        return false;
    };

    bt(0);

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            if(j) {
                cout << ' ';
            }
            if(g[i][j][0] == '.') {
                cout << ans[i][j];
            } else {
                cout << '_';
            }
        }
        cout << '\n';
    }
}

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

    int T = 1;
    // cin >> T;
    for(int test = 1; test <= T; test++) {
        read();
        solve();
    }

    return 0;
}
```

---

## 4. Python Solution with Detailed Comments

```python
import sys


def solve():
    # Read all input tokens.
    data = sys.stdin.read().strip().split()

    # First two tokens are n and m.
    n = int(data[0])
    m = int(data[1])

    # Remaining tokens describe the grid cells.
    tokens = data[2:]

    # Build the n x m grid of strings.
    g = []
    ptr = 0
    for _ in range(n):
        row = tokens[ptr:ptr + m]
        ptr += m
        g.append(row)

    # h_run[i][j] = horizontal run id of white cell (i, j), or -1.
    h_run = [[-1] * m for _ in range(n)]

    # v_run[i][j] = vertical run id of white cell (i, j), or -1.
    v_run = [[-1] * m for _ in range(n)]

    # Clue sums for horizontal and vertical runs.
    h_clue = []
    v_clue = []

    # Lengths of horizontal and vertical runs.
    h_count = []
    v_count = []

    # Scan all grid cells.
    for i in range(n):
        for j in range(m):
            s = g[i][j]

            # White cells and clue-less black cells do not start runs.
            if s[0] == "." or s == "XXXXX":
                continue

            # AA is the vertical clue part.
            aa = s[:2]

            # BB is the horizontal clue part.
            # s[2] is the backslash.
            bb = s[3:5]

            # Horizontal clue: run goes to the right.
            if bb != "XX":
                rid = len(h_clue)
                h_clue.append(int(bb))

                cnt = 0
                k = j + 1

                # Assign all consecutive white cells to this horizontal run.
                while k < m and g[i][k][0] == ".":
                    h_run[i][k] = rid
                    cnt += 1
                    k += 1

                h_count.append(cnt)

            # Vertical clue: run goes downward.
            if aa != "XX":
                rid = len(v_clue)
                v_clue.append(int(aa))

                cnt = 0
                k = i + 1

                # Assign all consecutive white cells to this vertical run.
                while k < n and g[k][j][0] == ".":
                    v_run[k][j] = rid
                    cnt += 1
                    k += 1

                v_count.append(cnt)

    # kak[length][sum] will contain all masks of distinct digits
    # with exactly "length" digits and total digit sum "sum".
    kak = [[[] for _ in range(46)] for _ in range(10)]

    # Digits are represented by bits 1..9.
    # Bit 0 is unused.
    for mask in range(1 << 10):
        # Ignore digit 0.
        if mask & 1:
            continue

        # Count digits in mask.
        cnt = mask.bit_count()

        # Compute sum of selected digits.
        total_sum = 0
        for d in range(1, 10):
            if mask & (1 << d):
                total_sum += d

        # Maximum possible digit sum is 45.
        if cnt <= 9 and total_sum <= 45:
            kak[cnt][total_sum].append(mask)

    # Number of runs.
    H = len(h_clue)
    V = len(v_clue)

    # Valid full masks for each actual horizontal run.
    h_subs = []
    for r in range(H):
        h_subs.append(kak[h_count[r]][h_clue[r]])

    # Valid full masks for each actual vertical run.
    v_subs = []
    for r in range(V):
        v_subs.append(kak[v_count[r]][v_clue[r]])

    # Collect all white cells.
    cells = []
    for i in range(n):
        for j in range(m):
            if g[i][j][0] == ".":
                cells.append((i, j))

    total_cells = len(cells)

    # Used digit masks for each run.
    h_used = [0] * H
    v_used = [0] * V

    # Whether each white cell has been filled.
    filled = [False] * total_cells

    # Answer grid. Only white cell entries matter.
    ans = [[0] * m for _ in range(n)]

    def allowed_for(subs, used):
        """
        Given:
        - subs: list of valid full masks for a run;
        - used: currently placed digits in that run.

        Return a bitmask of digits that can still be added.
        """
        allowed = 0

        # A full mask remains possible only if it contains all used digits.
        for t in subs:
            if (t & used) == used:
                allowed |= t

        # Already-used digits cannot be reused.
        return allowed & ~used

    def backtrack(placed):
        """
        Recursive search.
        placed = number of already-filled white cells.
        """
        # All white cells filled means success.
        if placed == total_cells:
            return True

        # Compute currently allowed extra digits for every horizontal run.
        h_allowed = [allowed_for(h_subs[r], h_used[r]) for r in range(H)]

        # Compute currently allowed extra digits for every vertical run.
        v_allowed = [allowed_for(v_subs[r], v_used[r]) for r in range(V)]

        # MRV choice: pick unfilled cell with fewest candidates.
        best = -1
        best_mask = 0
        best_cnt = 100

        for idx, (i, j) in enumerate(cells):
            if filled[idx]:
                continue

            # Candidate digits must work in both associated runs.
            cand = h_allowed[h_run[i][j]] & v_allowed[v_run[i][j]]

            # Number of possible digits.
            cnt = cand.bit_count()

            # Update best if this cell is more constrained.
            if cnt < best_cnt:
                best_cnt = cnt
                best = idx
                best_mask = cand

                # Cannot get better than 0 or 1.
                if cnt <= 1:
                    break

        # No candidate for some cell means dead end.
        if best_cnt == 0:
            return False

        # Chosen cell coordinates.
        i, j = cells[best]

        # Run IDs of chosen cell.
        hr = h_run[i][j]
        vr = v_run[i][j]

        # Mark cell filled.
        filled[best] = True

        # Try all digits in candidate mask.
        mask = best_mask
        while mask:
            # Extract lowest set bit.
            bit = mask & -mask

            # Convert bit to digit.
            d = bit.bit_length() - 1

            # Place digit in both run masks.
            h_used[hr] |= bit
            v_used[vr] |= bit

            # Store answer digit.
            ans[i][j] = d

            # Recurse.
            if backtrack(placed + 1):
                return True

            # Undo placement.
            h_used[hr] ^= bit
            v_used[vr] ^= bit

            # Remove this bit from iteration mask.
            mask &= mask - 1

        # Unmark chosen cell before returning failure.
        filled[best] = False

        return False

    # Puzzle is guaranteed solvable.
    backtrack(0)

    # Build output lines.
    output = []

    for i in range(n):
        row = []
        for j in range(m):
            if g[i][j][0] == ".":
                row.append(str(ans[i][j]))
            else:
                row.append("_")
        output.append(" ".join(row))

    print("\n".join(output))


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

---

## 5. Compressed Editorial

Parse all clue cells. A clue `AA\BB` creates a vertical run downward if `AA != XX` and a horizontal run rightward if `BB != XX`. Assign every white cell its horizontal and vertical run IDs.

Represent digit sets by bitmasks over bits `1..9`. Precompute all masks grouped by `(number of digits, digit sum)`. Thus, for each run, we know every possible complete digit set satisfying its length and clue.

Backtrack over white cells. Maintain `h_used` and `v_used`, the already-used digits in every run. For a run, a digit is currently allowed if it belongs to at least one valid full mask that contains the already-used mask. For a cell, candidates are the intersection of allowed digits from its horizontal and vertical runs.

Use MRV: always fill the unfilled cell with the fewest candidates. Try each candidate digit, update both run masks, recurse, and undo on failure.

When all white cells are filled, every run corresponds to one of its valid precomputed masks, so all sums and uniqueness constraints hold. Since a solution is guaranteed, the search finds one.
