#!/usr/bin/env python3

# This does now work. Falsely assumes that all letters "on the side" can be replaced by their minimum
# @EXPECTED_RESULTS@: WRONG_ANSWER, TIME_LIMIT_EXCEEDED

import itertools

lines = [list(input()) for _ in range(6)]

# Replace all side-faces with their minimum letter, to get the time down to 3^16

for i in range(16):
    lines[1][i] = min(lines[l][i] for l in range(1, 5))
lines = [lines[0], lines[1], lines[5]]

alphabet = [0, 1, 2]

solutions = set()
for string in itertools.product(alphabet, repeat=16):
    prev = '@' # precedes 'A'
    cost = 0
    for i, l in enumerate(string):
        char = lines[l][i]
        cost += l
        if char < prev:
            break
        prev = char
        if prev == 'Q':
            prev = 'U'
    else:
        solutions.add(cost)
print('impossible' if not solutions else min(solutions))
