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

454. Kakuro
Time limit per test: 2.75 second(s)
Memory limit: 65536 kilobytes
input: standard
output: standard



Kakuro puzzle is played on a nx m grid of "black" and "white" cells. Apart from the top row and leftmost column which are entirely black, the grid has some amount of white cells which form "runs" and some amount of black cells. "Run" is a vertical or horizontal maximal one-lined block of adjacent white cells. Each row and column of the puzzle can contain more than one "run". Every white cell belongs to exactly two runs — one horizontal and one vertical run. Each horizontal "run" always has a number in the black half-cell to its immediate left, and each vertical "run" always has a number in the black half-cell immediately above it. These numbers are located in "black" cells and are called "clues".

The rules of the puzzle are simple:
place a single digit from 1 to 9 in each "white" cell
each digit may only be used once in each "run"
for all runs, the sum of all digits in a "run" must match the clue associated with the "run"


Given the grid, your task is to find a solution for the puzzle.


Input
The first line of input contains two integers n and m (2 ≤ n,m ≤ 6) — the number of rows and columns correspondingly. Each of the next n lines contains descriptions of m cells. Each cell description is one of the following 5-character strings:
..... — "white" cell;
XXXXX — "black" cell with no clues;
AA\BB — "black" cell with one or two clues. AA is either a 2-digit clue for the corresponding vertical run, or XX if there is no associated vertical run. BB is either a 2-digit clue for the corresponding horizontal run, or XX if there is no associated horizontal run.
The first row and the first column of the grid will never have any white cells. The given grid will have at least one "white" cell.

It is guaranteed that the given puzzle has at least one solution.

Output
Print n lines to the output with m cells in each line. For every "black" cell print '' (underscore), for every "white" cell print the corresponding digit from the solution. Delimit cells with a single space, so that each row consists of 2m-1 characters.

If there are many solutions, you may output any of them.

Example(s)
sample input
sample output
6 6
XXXXX XXXXX 28\XX 17\XX 28\XX XXXXX
XXXXX 22\22 ..... ..... ..... 10\XX
XX\34 ..... ..... ..... ..... .....
XX\14 ..... ..... 16\13 ..... .....
XX\22 ..... ..... ..... ..... XXXXX
XXXXX XX\16 ..... ..... XXXXX XXXXX
_ _ _ _ _ _
_ _ 5 8 9 _
_ 7 6 9 8 4
_ 6 8 _ 7 6
_ 9 2 7 4 _
_ _ 7 9 _ _

sample input
sample output
3 3
XXXXX 04\XX XXXXX
XX\04 ..... XXXXX
XXXXX XXXXX XXXXX
_ _ _
_ 4 _
_ _ _

<|response|>
## 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), `XXXXX` (black no-clue), or `AA\BB` (clues). Output `_` for black cells and the chosen digit for white cells. The puzzle is guaranteed to have at least one solution.

---

## 2. Key observations

1. At most `36` cells in the grid, but `9^36` brute force is infeasible.

2. Constraints are grouped by **runs** (maximal sequences of white cells). Each white cell belongs to exactly one horizontal and one vertical run.

3. For each run with length `k` and clue sum `S`, only certain subsets of `{1..9}` of size `k` with sum `S` are valid. There are very few such subsets. **Precompute** all of them for every `(k, S)` pair.

4. Represent digit sets by **bitmasks** over bits `1..9` (bit 0 unused). Enumerate all `2^9` masks and group by `(popcount, sum)`.

5. During backtracking, for each run maintain `used`: digits already placed there. The digits still allowed in run `r` are the union of all valid masks that are supersets of `used`, minus `used` itself.

6. For each white cell, candidates = `allowed_horizontal & allowed_vertical`. This is much tighter than sum-range pruning.

7. **MRV heuristic**: always fill the unfilled cell with fewest candidates. Quickly detects dead ends.

---

## 3. Full solution approach

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 `h_run[i][j]` and `v_run[i][j]` run IDs.

Precompute `kak[len][sum]`: list of all bitmasks with exactly `len` bits set among `{1..9}` summing to `sum`.

For each actual run, retrieve its list of valid masks from `kak[length][clue]`.

Backtrack: maintain `h_used[r]` and `v_used[r]`. At each step, compute per-run allowed sets from valid-mask supersets, then compute per-cell candidates as the bitwise AND of its two runs' allowed sets. Pick the cell with fewest candidates (MRV), try each candidate digit, recurse.

When all cells are filled, every run's used mask is one of its precomputed valid masks, guaranteeing correctness.

---

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

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

---

## 5. Python implementation (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()
```
