import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; public class SolutionIvan { public static void main(String[] args) throws IOException { new SolutionIvan().run(); } BufferedReader input; StringTokenizer tokenizer; String next() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(input.readLine()); } return tokenizer.nextToken(); } static int INF = 1000000000; public int getCost(int index) { if (index == 0) { return 0; } if (index > 0 && index < 5) { return 1; } return 2; } public void update(Map costs, char c, int cost) { if (!costs.containsKey(c)) { costs.put(c, INF); } costs.put(c, Math.min(cost, costs.get(c))); } public static boolean canPreceed(char lhs, char rhs) { if (lhs == 'Q') { lhs = 'U'; } return lhs <= rhs; } public int solve(List> dice) { Map costs = new HashMap<>(); List lastDie = dice.get(dice.size() - 1); for (int i = 0; i < 6; ++i) { int cost = getCost(i); update(costs, lastDie.get(i), cost); } for (int dieIndex = dice.size() - 2; dieIndex >= 0; --dieIndex) { List die = dice.get(dieIndex); Map newCosts = new HashMap<>(); for (int i = 0; i < 6; ++i) { int cost = getCost(i); char lhs = die.get(i); int newValue = costs.keySet().stream().filter(c -> canPreceed(lhs, c)) .map(costs::get).min(Integer::compare).orElse(INF) + cost; if (newValue < INF) { update(newCosts, lhs, newValue); } } costs = newCosts; } return costs.values().stream().min(Integer::compare).orElse(INF); } public void run() throws IOException { input = new BufferedReader(new InputStreamReader(System.in)); String up = next(); List sides = new ArrayList<>(4); for (int i = 0; i < 4; ++i) { sides.add(next()); } String down = next(); List> dice = new ArrayList<>(16); for (int i = 0; i < 16; ++i) { List die = new ArrayList<>(6); die.add(up.charAt(i)); for (int j = 0; j < 4; ++j) { die.add(sides.get(j).charAt(i)); } die.add(down.charAt(i)); dice.add(die); } int ans = solve(dice); if (ans >= INF) { System.out.println("impossible"); } else { System.out.println(ans); } } }