#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++) bitset<4> mam; bool suvis(bool a[4][4]) { queue q; bitset<4> bol; bol.reset(); int z = -1; REP(i,4) if (mam[i]) z = i; if (z == -1) return false; for (q.push(z); !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 == mam) 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; vector p(2*h-1); REP(i,h) p[i] = h-i-1; FOR(i,h,2*h-1) p[i] = i-h+1; int tmp = 2*h-1; mam.reset(); REP(i,p.size()) { oo[i].clear(); int pos = p[i], kol = 2*h-1-pos; s[i] = string(pos+kol*2, ' '); REP(j,kol) { scanf("%s", t); s[i][pos] = t[0]; if ('A'<=s[i][pos] && s[i][pos]<='D') mam [s[i][pos]-'A'] = true;; oo[i].push_back(pos); pos += 2; } } REP(i,tmp) REP(j,s[i].size()) REP(k,4) vz[i][j][k] = 12345678; REP(i,tmp) 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(k,0) REP(i,2*h-1) { REP(j,s[i].size()) if (s[i][j] != ' ') cout< ce(16, 12345678); REP(i,16) { bitset<4> b(i); 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; } ce[i] = min(ce[i], teraz); } } REP(i,16) REP(j,16) REP(k,16) if ( (i|j|k) == mam.to_ulong()) { bool a[4][4]; memset(a, 0x00, sizeof(a)); int x[]={i, j, k}; int cena = 0; REP(l,3) { cena += ce[x[l]]; bitset<5> b(x[l]); REP(iq,4) if (b[iq]) REP(jq,4) if (b[jq]) a[iq][jq] = true; if (suvis(a)) res = min(res, cena); } } printf("You have to buy %d parcels.\n", res); } }