Logic Puzzle
Time limit1sMemory limit512 MB
Given a grid of variable names with row and column sums, deduce each variable's integer value by repeatedly solving rows or columns with a single unknown.
- Level
Medium4 of 10
- Topics
- Simulation, Implementation
- Solved
- No attempts yet
Problem
The grid below is a logic puzzle of the kind printed in puzzle magazines. Every cell of the grid holds one variable name, and the numbers written to the right of the grid and under it are the sums of the values of the variables in each row and in each column.

The goal is to give every variable a value so that all of the row sums and the column sums hold. The puzzle is made for children, so it has one property that helps: there is always a row or a column in which exactly one variable still has an unknown value. You can fix the value of one variable at each step until no unknown variable is left.
Given a puzzle, determine the value of every variable.
Input
The first line contains two integers and , the number of rows and the number of columns of the puzzle (, ). Each of the next lines contains variable names followed by an integer , the sum of the values of the variables in that row (). The last line contains integers, where the -th integer is the sum of the values of the variables in column ().
A variable name is exactly two lowercase letters from 'a' to 'z'. The same name may appear in several cells, and each appearance adds that value to the sum again. Every puzzle has a unique solution, and every variable value is an integer between and .
Output
Print one line for each variable of the puzzle, containing the variable name and its integer value separated by a space. Print the variables in increasing alphabetical order, that is aa, ab, ..., az, ba, bb, ..., za, zb, ..., zz.