import sys


def get_final_score(board, numbers):
    number_to_turn = {number: turn for turn, number in enumerate(numbers)}

    row_bingo_turns = [max(number_to_turn[n] for n in r) for r in board]
    column_bingo_turns = [max(number_to_turn[n] for n in c) for c in zip(*board)]
    bingo_turn = min(min(row_bingo_turns), min(column_bingo_turns))

    score = sum(n for r in board for n in r if number_to_turn[n] > bingo_turn)
    return bingo_turn, score * numbers[bingo_turn]


def main():
    numbers_str, *board_strs = sys.stdin.read().split("\n\n")
    numbers = [int(s) for s in numbers_str.split(",")]

    boards = [
        [[int(word) for word in line.split()] for line in board_str.splitlines()]
        for board_str in board_strs
    ]

    final_scores = [get_final_score(board, numbers) for board in boards]

    for _, final_score in [min(final_scores), max(final_scores)]:
        print(final_score)


if __name__ == "__main__":
    main()
