Borg Maze
64-bit integer IO format: %lld Java class name: Main
Your task is to help the Borg (yes, really) by developing a program which helps the Borg to estimate the minimal cost of scanning a maze for the assimilation of aliens hiding in the maze, by moving in north, west, east, and south steps. The tricky thing is that the beginning of the search is conducted by a large group of over 100 individuals. Whenever an alien is assimilated, or at the beginning of the search, the group may split in two or more groups (but their consciousness is still collective.). The cost of searching a maze is definied as the total distance covered by all the groups involved in the search together. That is, if the original group walks five steps, then splits into two groups each walking three steps, the total distance is 11=5+3+3.
Input
Output
Sample Input
2 6 5 ##### #A#A## # # A# #S ## ##### 7 7 ##### #AAA### # A# # S ### # # #AAA### #####
Sample Output
8 11
Source
1 #include <iostream> 2 #include <cstdio> 3 #include <queue> 4 #include <cstring> 5 #define INF 0x3f3f3f3f 6 #define pii pair<int,int> 7 using namespace std; 8 const int maxn = 110; 9 const int mx = 1000000; 10 int e[maxn][maxn],d[maxn][maxn],hs[maxn][maxn],ds[mx],n,m,tot; 11 bool done[mx]; 12 char mp[maxn][maxn]; 13 bool isIn(int x,int y) { 14 return x >=0 && x < n && y >= 0 && y < m; 15 } 16 void bfs(int x,int y) { 17 queue< pii >q; 18 q.push(make_pair(x,y)); 19 memset(d,-1,sizeof(d)); 20 d[x][y] = 0; 21 static const int dir[4][2] = {-1,0,1,0,0,-1,0,1}; 22 while(!q.empty()) { 23 pii now = q.front(); 24 q.pop(); 25 for(int i = 0; i < 4; ++i) { 26 int tx = now.first + dir[i][0]; 27 int ty = now.second + dir[i][1]; 28 if(isIn(tx,ty) && mp[tx][ty] != '#' && d[tx][ty] == -1) { 29 d[tx][ty] = d[now.first][now.second] + 1; 30 q.push(make_pair(tx,ty)); 31 if(mp[tx][ty] == 'A' || mp[tx][ty] == 'S') { 32 e[hs[x][y]][hs[tx][ty]] = d[tx][ty]; 33 } 34 } 35 } 36 } 37 } 38 39 int prim() { 40 int ans = 0,cnt = 0; 41 for(int i = 0; i < tot; ++i) { 42 done[i] = false; 43 ds[i] = INF; 44 } 45 ds[0] = 0; 46 while(true) { 47 int minV = INF,idx = -1; 48 for(int i = 0; i < tot; ++i) 49 if(ds[i] < minV && !done[i]) minV = ds[idx = i]; 50 if(minV == INF || idx == -1) break; 51 ans += minV; 52 done[idx] = true; 53 for(int i = 1; i < tot; ++i) 54 if(!done[i] && e[idx][i] < ds[i]) ds[i] = e[idx][i]; 55 } 56 return ans; 57 } 58 59 int main() { 60 int kase; 61 scanf("%d",&kase); 62 while(kase--) { 63 scanf("%d %d",&m,&n); 64 gets(mp[0]); 65 for(int i = tot = 0; i < n; ++i) { 66 gets(mp[i]); 67 for(int j = 0; j < m; ++j) { 68 if(mp[i][j] == 'A' || mp[i][j] == 'S') 69 hs[i][j] = tot++; 70 } 71 } 72 for(int i = 0; i < n; ++i) { 73 for(int j = 0; j < m; ++j) 74 if(mp[i][j] == 'A' || mp[i][j] == 'S') bfs(i,j); 75 } 76 printf("%d\n",prim()); 77 } 78 return 0; 79 }