Logic Puzzle

Time limit1sMemory limit512 MB

Summary
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 LL and CC, the number of rows and the number of columns of the puzzle (1≤L≤1001 \le L \le 100, 1≤C≤1001 \le C \le 100). Each of the next LL lines contains CC variable names followed by an integer SS, the sum of the values of the variables in that row (−108≤S≤108-10^8 \le S \le 10^8). The last line contains CC integers, where the ii-th integer XiX_i is the sum of the values of the variables in column ii (−108≤Xi≤108-10^8 \le X_i \le 10^8).

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 −106-10^6 and 10610^6.

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.

Examples3

  1. Example 1

    Input
    4 5
    df bb cg df df 11
    ee az cg az ee 6
    df cg cg df df 10
    az az cg az az 6
    6 7 8 6 6
    
    Expected output
    az 1
    bb 3
    cg 2
    df 2
    ee 1
    
  2. Example 2

    Input
    3 4
    aa bb cc dd 10
    aa bb cc dd 10
    aa bb cc dd 10
    3 6 9 12
    
    Expected output
    aa 1
    bb 2
    cc 3
    dd 4
    
  3. Example 3

    Input
    3 3
    aa zz aa 27
    vv zz aa -5
    kk kk aa 40
    15 -7 54
    
    Expected output
    aa 18
    kk 11
    vv -14
    zz -9