#include #include #include using namespace std; int pm[25][42]; int rs[23]; int d, i, j, k, n, T, M, S, r; char a[1048579], z; char b[1048579]; char c[1048579]; int nas[23]; queue > q; int main() { while (scanf("%d", &d), d > 0) { n = 1; for (i = 0; i < d; i++) { scanf("%d", &rs[i]); if (i == 0) nas[0] = rs[0]; else nas[i] = nas[i - 1] * rs[i]; n *= rs[i]; } for (i = 0; i < n; i++) { while ((z = getchar()) == '\n'); a[i] = b[i] = c[i] = z; if (z == 'T') T = i; if (z == 'S') S = i; if (z == 'M') {M = i;a[i] = '#';} } q.push(make_pair(0, T)); while (!q.empty()) { i = q.front().second; k = q.front().first; q.pop(); if (i == S) break; a[i] = '#'; for (j = 0; j < d; j++) { r = i % nas[j]; if (j > 0) r /= nas[j-1]; if (r > 0) { i -= j > 0 ? nas[j-1] : 1; if (a[i] != '#') q.push(make_pair(k+1, i)); i += j > 0 ? nas[j-1] : 1; } if (r < rs[j] - 1) { i += j > 0 ? nas[j-1] : 1; if (a[i] != '#') q.push(make_pair(k+1, i)); i -= j > 0 ? nas[j-1] : 1; } } } if (i != S) printf("No solution. Poor Theseus!\n"); continue; while (!q.empty()) q.pop(); q.push(make_pair(k, S)); while (!q.empty()) { i = q.front().second; k = q.front().first; q.pop(); if (i == M) break; b[i] = '#'; for (j = 0; j < d; j++) { r = i % nas[j]; if (j > 0) r /= nas[j-1]; if (r > 0) { i -= j > 0 ? nas[j-1] : 1; if (b[i] != '#') q.push(make_pair(k+1, i)); i += j > 0 ? nas[j-1] : 1; } if (r < rs[j] - 1) { i += j > 0 ? nas[j-1] : 1; if (b[i] != '#') q.push(make_pair(k+1, i)); i -= j > 0 ? nas[j-1] : 1; } } } if (i != M) printf("No solution. Poor Theseus!\n"); continue; while (!q.empty()) q.pop(); q.push(make_pair(k, M)); while (!q.empty()) { i = q.front().second; k = q.front().first; q.pop(); if (i == T) break; c[i] = '#'; for (j = 0; j < d; j++) { r = i % nas[j]; if (j > 0) r /= nas[j-1]; if (r > 0) { i -= j > 0 ? nas[j-1] : 1; if (c[i] != '#') q.push(make_pair(k+1, i)); i += j > 0 ? nas[j-1] : 1; } if (r < rs[j] - 1) { i += j > 0 ? nas[j-1] : 1; if (c[i] != '#') q.push(make_pair(k+1, i)); i -= j > 0 ? nas[j-1] : 1; } } } if (i != T) printf("No solution. Poor Theseus!\n"); continue; printf("Theseus needs %d steps.\n", k); } return 0; }