#include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef pair PI; #define REP(i,n) for (int i=0; i=0; i--) #define FOREACH(it,a) for (__typeof(a.begin()) it=a.begin(); it!=a.end(); it++) bool suvis(bool a[4][4]) { queue q; vector bol(4, false); bol[0] = true; for (q.push(0); !q.empty(); q.pop()) { int u = q.front(); REP(j,4) if (!bol[j] && a[u][j]) { q.push(j); bol[j] = true; } } if (bol == vector(4, true)) return true; return false; } int vz[200][200][4], e[200][200]; int main() { int h; char t[50]; string s[100]; vector oo[100]; int sx[]={-1, -1, 0, 1, 1, 0}, sy[]={-1, 1, 2, 1, -1, -2}; while (scanf("%d", &h) == 1) { if (!h) break; fgets(t, 100, stdin); REP(i,2*h-1) { fgets(t, 100, stdin); s[i] = t; s[i].resize(s[i].size()-1); oo[i].clear(); REP(j,s[i].size()) if (s[i][j] != ' ') oo[i].push_back(j); } REP(i,2*h-1) REP(j,s[i].size()) REP(k,4) vz[i][j][k] = 12345678; REP(i,2*h-1) REP(ij,oo[i].size()) { int j = oo[i][ij]; REP(l,2*h-1) REP(k,oo[l].size()) e[l][oo[l][k]] = 12345678; queue q; e[i][j] = 0; for (q.push(PI(i, j)); !q.empty(); q.pop()) { int tx=q.front().first, ty=q.front().second; if ('A'<=s[tx][ty] && s[tx][ty]<='D') vz[i][j][ s[tx][ty]-'A' ] = min(e[tx][ty], vz[i][j][ s[tx][ty]-'A' ]); REP(d,6) { int nx=tx+sx[d], ny=ty+sy[d]; if (nx >= 2*h-1 || nx <0 || ny < 0 || ny >= int(s[nx].size())) continue; if (e[nx][ny] < 12345678 || s[nx][ny] == ' ') continue; e[nx][ny] = e[tx][ty]+1; q.push(PI(nx, ny)); } } } /* REP(i,2*h-1) { REP(j,s[i].size()) if (s[i][j] != ' ') cout< b(x[l]); int mi = 12345678; REP(iz,2*h-1) REP(jjz,oo[iz].size()) { int jz = oo[iz][jjz]; int teraz = 0; if (s[iz][jz] == '.') teraz++; REP(iq,4) if (b[iq]) { int yy = vz[iz][jz][iq]-1; if (yy < 0) yy = 0; teraz += yy; } mi = min(mi, teraz); } cena += mi; REP(iq,4) REP(jq,4) if (b[iq] && b[jq]) a[iq][jq] = true; if (suvis(a)) res = min(res, cena); } } printf("You have to buy %d parcels.\n", res); } }